How to print a single word out of a user input

Tal Ouzan :

How do i print out a single word out of a user input in java? example: user input:"We love mom she is the best". the program suppose to print "mom" because of first and last chars are the same. my code does not print anything at the end. Here is my code:

      Scanner s = new Scanner(System.in);
        System.out.println("Please enter a Sentence");
        String input=s.nextLine();
        String builderString=" ";
        for(int i=0,j=0;i<input.length();i++){
            if(input.charAt(i)==' '){
                j=i+1; //upper the value of J if there is space (J will always check first char)
                if (input.charAt(j)==input.charAt(i)&&j<i) {//an if statement to check for match chars.
                        builderString=" "+input.charAt(i);// insert the char into a new string to print it in the console.
                    }
                }
            }
        }
        System.out.println(builderString);
    }
}
Nicolas :

Rather than parsing every letter of the string, you could split your input into an array of words and check each word individually.

You can keep your loop but you just have to check if the chart at 0 is the same than the one at word.length() - 1

Here is a working example. Please note that i've remove the scanner part to make it work in the playground i'm using.

// This would be de equivalent of your scanner
String input = "We love mom she is the best";


String[] words = input.split(" ");
String output = "";
for(int i=0;i<words.length; i++){
   String currentWord = words[i];
   if(currentWord.charAt(0) == currentWord.charAt(currentWord.length() -1)) {
       output = currentWord;
    }
}   

System.out.println(output);   

You also don't need your j variable no more.

You can test it out here

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416427&siteId=1