QNA > H > How To Extract Words From A String In Java

How to extract words from a string in Java

We can extract words from a string in many way , but here I am giving some way to extract a word from string

In Java:

Java String indexOf()

The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

String str=”Java is a programming language";

int prgindex=str.indexOf(“programming”);

int langindex=str.indexOf(“language);

String word=str.substring(prgindex, langindex);

System.out.println(word);

Other way:

Java String split()

The java string split() method splits this string against given regular expression and returns a char array.

String str=”Java is a programming language";

String [] words=str.split(“ “);// split by space

System.out.println(“to print specified word:”+words[3]);

In above code it print word which is at 3rd index.

If you want to print all words we can use loop or foreach etc..

Example:

String str=”Java is a programming language";

String [] words=str.split(“ “);// split by space

for(int I=0;I

{

System.out.println(“word “+(I+1)+” : “+words[I]);

}

Thank you

Di Toole Chaton

Come stampare SMS Android :: Quali sono i migliori giochi di scacchi per PC?
Link utili