Reputation: 69
I am trying to find the shortest word from a string array, but I am removing special characters using reg ex with the code
public String[] setWordArray(String stringToBeAnaylsedForFrequency) {
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("\\d+", " ");
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("\\W", " ");
stringToBeAnaylsedForFrequency = stringToBeAnaylsedForFrequency.replaceAll("( )+ ", " ");
String[] wordArray = stringToBeAnaylsedForFrequency.split(" ");
return wordArray;
}
and this is the method for use
public String getShortestWordInStringGiven() {
int wordArrayLength = getStringArrayForGivenString().length;
String shortestWordInGivenString = getStringArrayForGivenString()[0];
for (int i = 1; i < wordArrayLength ; i++) {
if (getStringArrayForGivenString()[i].length() < shortestWordInGivenString.length()) {
shortestWordInGivenString = getStringArrayForGivenString()[i];
}
}
return shortestWordInGivenString;
}
when it works fine i input text like hello you, it would return you as the shortest character, but when i input "hello you" with a special character at the start it returns nothing.
Upvotes: 0
Views: 442
Reputation: 48057
Answering to your comments: When you have a space in the beginning, split
will have one more element, an empty String, in the beginning. That one is the shortest element in the array (check for the array's length), but printing it reveals nothing that's visible. But, rest assured, the correct element is printed: it's ""
You might want to trim
your String before the split
operation
Upvotes: 2