Aug 202011
 
Java Search String For Index

Java has very good methods for searching a sub string within another string: indexOf and lastIndexOf. In this part I will demonstrate the uses of these methods.

package net.searchdaily.java.string.common;

/**
 * Java String Search. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class JavaSearchString {
	public static void main(String[] args) {
		// the given string to search
		String stringText = "Java String to execute the String Search methods";
		String textToSearch = "String"; // we will search for "String" in the
										// stringText

		int foundPosition = stringText.indexOf(textToSearch);

		System.out.println("I found: " + textToSearch + " in " + stringText
				+ " at the position: " + foundPosition);
	}
}

In the above example, the result will be 5 as it the first location where String is found in the text “Java String to execute the String Search methods”

image thumb70 Java String common uses part 2

How about the case when search string cannot be found? the indexOf method will return a negative number (-1). See it in the next example where I use the same example above to search for String starts from specific location.

Continue reading »