C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
CharAt: We use the charAt method to count spaces. We decrement the "words" count when a space is encountered.
charAtSubstring: When no more words are needed, we return a string of the word up to the current space. This substring contains the first words.
SubstringJava program that gets first words from string
public class Program {
public static String firstWords(String input, int words) {
for (int i = 0; i < input.length(); i++) {
// When a space is encountered, reduce words remaining by 1.
if (input.charAt(i) == ' ') {
words--;
}
// If no more words remaining, return a substring.
if (words == 0) {
return input.substring(0, i);
}
}
// Error case.
return "";
}
public static void main(String[] args) {
String value = "One two three four five.";
System.out.println(value);
// Test firstWords on the first 3 and 4 words.
String words3 = firstWords(value, 3);
System.out.println(words3);
String words4 = firstWords(value, 4);
System.out.println(words4);
}
}
Output
One two three four five.
One two three
One two three four