使用indexOf实现检索
indexOf方法用于实现在字符串中检索另外一个字符串 String提供几个重载的indexOf方法 1). **int indexOf(String str)在字符串中检索str,返回其第一次出现的位置,如果找不到则返回-1 2). int indexOf(String str,int fromIndex)**从字符串的fromIndex位置开始检索String还定义有lastIndexOf方法 1). **int lastIndexOf(String str,int form)**str在字符串中多次出现时,将返回最后一个出现的位置 public void testIndexOf() { Stringstr = "I can because i think i can"; int index = str.indexOf(" can"); System.out.println(index); // 2 index = strlastIndexOf(" can"); System.out.println(index); // 24 index = str.indexOf("can", 6); System.out.println(index); // 24 index = str.indexOf(" Can"); System.out.println(index); // -1 substring获取字符串 substring方法用于返回一个字符串的子字符串 substring常用重载方法定义如下 1).**String substring(int beginIndex,int endIndex)**返回字符串中从下标beginIndex(包括)开始到endIndex(不包括)结束的子字符串 2).String sunstring(int beginIndex)返回字符串从下标beginIndex开始到字符串结尾的子字符串 public void testSubstring() { Stringstr = "http://www.oracle.com"; String subStr = str.substring(11, 17 ); System.out.println(subStr); // oracle subStr = str.substring( 7 ); System.out.println(subStr); // www.oracle.com } **trim()**去掉一个字符串前后空白 public void testTrim() { String userName =" good man " userName = userName.trim(); System.out. println( userName.length ( ) ); // 8 Syste m. out. println(userName); // good man } **cahrAt(int index)**返回字符串指定位置的字符.参数index表示指定位置startsWith()和endsWith() 检查一个字符串是否以指定字符串开头或者结尾 public void testStartWithAndEndWith() { String str = " Thinking in Java"; System. out. println(str.endsWith("Java")); // true System. out. println(str.startsWith("T"));// true System. out.println(str.startsWith(" thinking”)); // false toUpperCase() ----------转大写toLowerCase()-----------转小写isEmpty();--------------检查空字符串length()----------------字符串长度