Reputation: 2785
What is the easiest way to find the number of characters in a sentence before nth word ?
For eg. :
String sentence = "Mary Jane and Peter Parker are friends."
int trigger = 5; //"Parker"
Output would be
Character count = 20
Any help will be appreciated. Thanks.
Upvotes: 0
Views: 140
Reputation: 94
public int getNumberOfCharacters(int nthWord){
String sentence = "Mary Jane and Peter Parker are friends.";
String[] wordArray = sentence.split(" ");
int count = 0;
for(int i=0; i<=nthWord-2 ; i++){
count = count + wordArray[i].length();
}
return count + (nthWord-1);
}`
try this it should work
Upvotes: 1
Reputation: 4392
Using regex can be done like this:
public static void main(String[] args) {
String sentence = "Mary Jane and Peter Parker are friends.";
int trigger = 5;
Pattern pattern = Pattern.compile(String.format("(?:\\S+\\s+){%d}(\\S+)", trigger - 1));
Matcher matcher = pattern.matcher(sentence);
matcher.find();
System.out.println(matcher.group().lastIndexOf(" ") + 1);
}
I am going through all the trouble of finding the exact work instead of simply indexOf("Parker")
because of possible duplicates.
The regex will match N words without capturing and capture the N+1 word. In your case it will match all previous words up to the one you want and capture the next one.
Upvotes: 0
Reputation: 137084
Easiest way would just be to loop around the characters in the String and count the number of white-spaces.
The following increments a length
variable for every character. When a white-space is encountered, we decrement the number of remaining white-spaces to read, and when that number reaches 1, it means we hit the wanted word, so we break out of the loop.
public static void main(String[] args) {
String sentence = "Mary Jane and Peter Parker are friends.";
int trigger = 5; //"Parker"
int length = 0;
for (char c : sentence.toCharArray()) {
if (trigger == 1) break;
if (c == ' ') trigger--;
length++;
}
System.out.println(length); // prints 20
}
Upvotes: 1