I have different types of names. Like
ABC BCD, EFG HGF, HGF HJK
I want to replace the last ,
with "and"
. So, the format will be like this
ABC BCD, EFG HGF & HGF HJK
I tried with this
names = "Jon Benda, Jon Wetchler, Thomas Leibig "
StringBuilder sbd = new StringBuilder();
String[] n = getNames.split("\\s+");
System.out.println(n.length);
for (int i = 0; i < n.length; i++) {
sbd.append(n[i]);
System.out.print(n[i]);
if (i < n.length - 3)
sbd.append(" ");
else if (i < n.length - 2)
sbd.append(" & ");
}
System.out.print("\n");
System.out.print(sbd);
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
String listOfWords = "This is a sentence"; String[] b = listOfWords. split("\\s+"); String lastWord = b[b. length - 1]; And then getting the rest of the the string by using the remove method to remove the last word from the string.
To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters. Retrieves a substring from this instance.
We can eliminate the leading and trailing spaces of a string in Java with the help of trim(). trim() method is defined under the String class of java. lang package.
Why to over complicate it? You can search for the last index of ,
using String#lastIndexOf
and then use StringBuilder#replace
:
int lastIdx = names.lastIndexOf(",");
names = new StringBuilder(names).replace(lastIdx, lastIdx+1, "and").toString();
You can do something like this.
public static void main(String[] args) {
String names = "Jon Benda, Jon Wetchler, Thomas Leibig ";
String newNames = "";
StringBuilder sbd = new StringBuilder();
String[] n = names.split(",");
System.out.println(n.length);
for (int i = 0; i < n.length; i++) {
if (i == n.length - 1) {
newNames = newNames + " and " + n[i];
} else {
newNames = newNames + n[i] + " ";
}
}
System.out.println(newNames);
}
This outputs
Jon Benda Jon Wetchler and Thomas Leibig
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With