本示例说明了如何使用indexOf()
方法在String对象中搜索单词,如果找到,该方法将返回单词在字符串中的位置索引。否则,它返回-1。
public class SearchStringEmp { public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) { System.out.println("Hello not found"); } else { System.out.println("Found Hello at index " + intIndex); } } }
输出结果
上面的代码示例将产生以下结果。
Found Hello at index 0