Program to split the words in sentence of string without using split in Java
In this program, you'll learn how to split the words in sentence of string without using split() function.
Hello Guys, if you know about split( ) method of String class, it can be used to split the sentence into words.
Here in this program we will split the using without using this split() method. So let us start.
import java.util.Scanner;
import java.util.ArrayList;
public class SplitSentenceIntoWords {
public static void main(String args[]) {
int i, index = 0;
ArrayList words = new ArrayList();
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence:");
String text = in.nextLine();
for(i = 0; i < text.length(); i++) {
if(text.charAt(i) == ' ') {
// If space found then consider it as word and add it to ArrayList
words.add(text.substring(index, i));
index = i + 1;
}
}
words.add(text.substring(index)); // Adding last word
System.out.println("\nWords in the sentence are....");
for(String s: words) {
System.out.println(s.length());
}
System.out.println("Total no. of words in given sentence = " + words.size());
}
}
OUTPUT
C:\>javac SplitSentenceIntoWords.java
C:\>java SplitSentenceIntoWords
Enter the sentence: Hello How are you Words in the sentence are.... Hello How are you Total no. of words in given sentence = 4