Skip to content
Advertisement

Finding Index of same element multiple times, Java

I have my code here, I enter a full name with three words, and I need to get the initials of the first two words, Like:

Input = Anthony Edward Stark

Output = A.E.Stark

Pls help me

Advertisement

Answer

I think this would do the job

public static void main(String[] args) {
        String input = "Anthony Edward Stark";
        String names[] = input.split(" ");
        String result = "";
        for(int i = 0; i<names.length; i++){
            if(i< names.length-1){
                result += names[i].charAt(0) +".";
            }else{
                result += names[i];
            }
        }
        System.out.println(result);
    }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement