Indexing every word in a string

You can just split your text on space, removing punctuation along the way, and then iterate through the array and print the indices:

String line = "hello, how are you?";
String[] words = line.replaceAll("[^a-zA-Z ]", "").split("\\s+");

for (int i=0; i < words.length; ++i) {
    System.out.print(words[i] + ":" + i + " ");
}

Explanation:

  • replaceAll("[^a-zA-Z ]", "") matches any character which is not a lowercase or uppercase letter and removes it
  • split("\\s+") splits the sentence, using one more whitespace characters as the point for the split

Browse More Popular Posts

Leave a Comment