Home
Java
String First Words
Updated Sep 11, 2023
Dot Net Perls
First words. A string contains many words. These are separated by spaces. To create a caption of the text, we sometimes need to get the first words from the string.
With a loop, and a char-testing algorithm, we can extract the first N words from a string. We use substring() to extract the first part from the text.
for
An example. Here is the firstWords method. This method receives two arguments: the string we want to get the first words from, and the number of words to extract. It uses a for-loop.
Start We use the charAt method to count spaces. We decrement the "words" count when a space is encountered.
String charAt
Return When no more words are needed, we return a string of the word up to the current space. This substring contains the first words.
String substring
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); } }
One two three four five. One two three One two three four
Some issues. The method does not handle an invalid number of words. If you specify a million words and there are not that many words, an empty string will be returned.
String isEmpty
A learning exercise. When learning a programming language, writing many simple methods like this one is helpful. Many things can be accomplished with a simple char-testing loop.
Summary. This method extracts the first words from a string. This can be used to create brief summaries of text (or captions for images). First words are often sufficient for labels.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen