How to remove the middle name from a full name in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        String name = "James John William";
 
        System.out.println(name);
 
        int index1 = name.indexOf(" ");
        int index2 = name.lastIndexOf(" ");
 
        if (index1 != index2 && index1 >= 0) {
            name = name.substring(0, index1 + 1) + name.substring(index2 + 1, name.length());
            System.out.println(name);
        }
    }
}




/*
run:
    
James John William
James William
    
*/

 



answered Nov 23, 2021 by avibootz

Related questions

1 answer 180 views
1 answer 155 views
1 answer 207 views
1 answer 170 views
1 answer 233 views
...