Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java removing the last string

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);
like image 886
user2579475 Avatar asked Aug 07 '13 07:08

user2579475


People also ask

How do you remove the last of a string in Java?

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.

How do I remove the last word in Java?

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.

How do I remove the last 3 characters from a 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.

How do I remove a trailing character in Java?

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.


2 Answers

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();
like image 140
Maroun Avatar answered Nov 19 '22 08:11

Maroun


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 
like image 29
Prasad Kharkar Avatar answered Nov 19 '22 08:11

Prasad Kharkar