-
/*Java Search String using indexOf ExampleThis example shows how we can search a word within a String object usingindexOf method.*/
public class SearchStringExample
{
public static void main(String[] args)
{//declare a String objectString strOrig = “Hello world Hello World”;
/*To search a particular word in a given string use indexOf method.indexOf method. It returns a position index of a word within the stringif found. Otherwise it returns -1.*/
int intIndex = strOrig.indexOf(“Hello”);
if(intIndex == – 1){System.out.println(“Hello not found”);}else{System.out.println(“Found Hello at index “ + intIndex);}
/*we can also search a word after particular position usingindexOf(String word, int position) method.*/
int positionIndex = strOrig.indexOf(“Hello”,11);System.out.println(“Index of Hello after 11 is “ + positionIndex);
/*Use lastIndexOf method to search a last occurrence of a word within string.*/int lastIndex = strOrig.lastIndexOf(“Hello”);System.out.println(“Last occurrence of Hello is at index “ + lastIndex);
}}
/*Output of the program would be :Found Hello at index 0Index of Hello after 11 is 12Last occurrence of Hello is at index 12*/
-
/*Java Char Array To String ExampleThis Java char array to String example shows how to convert char array toString in Java.*/public class CharArrayToStringExample{public static void main(String args[]){//char arraychar[] charArray = new char[]{‘J’,‘a’,‘v’,‘a’};/** To convert char array to String in Java, use* String(Char[] ch) constructor of Java String class.*/String str = new String(charArray);System.out.println(“Char array converted to String: “ + str);}}/*Output of above given char array to String example would beChar array converted to String: Java*/