字符串的查找
(1)indexOf(value);
(2)indexOf(value, int fromIndex);
(3)lastIndexOf(value);
(4)lastIndexOf(value, int fromIndex);
(5)chatAt(int index);
下面展示一些 内联代码片
。
public static void main(String[] args) {
String str = "neugiwiwih";
//返回指定字符串首次出现的索引值,否则返回-1
System.out.print(str.indexOf("n"));
//指定查找时起始索引为6
System.out.print(str.indexOf("i",6));
//返回指定字符串最后一次出现的索引值,否则返回-1
System.out.print(str.lastIndexOf("i"));
//查找策略:从右往左查,查找索引位置为5之前的指定字符串
System.out.print(str.lastIndexOf("i",5));
//根据指定索引值查找字符
System.out.print(str.charAt(0));
}
字符串的替换
(1)replace(String OldChar, String NewChar);
(2)replaceFirst(String regex,String replacement);
(3)replaceAll(String regex, String replacement);
下面展示一些 内联代码片
。
String str = " Hello,my life Hello,my friends ";
String s = "983the38y";
System.out.print(str.replace("l", "G"));
System.out.print(str.replace("Hello", "你好"));
System.out.print(str.replaceFirst("Hello", "你好"));
System.out.print(str.replaceAll("Hello", "你好"));
//replace()、replaceAll()区别:后者可以用正则表达式和字符替换
System.out.print(s.replaceAll("\\D", ""));
System.out.print("\n");
StringBuffer类的常用方法
下面展示一些 内联代码片
。
//StringBuffer
StringBuffer strb = new StringBuffer("hello,");
//追加字符串
System.out.print(strb.append("world!"));
//替换字符
strb.setCharAt(0, 'H');
System.out.print(strb);
System.out.print("\n");
//左闭右开
System.out.print(strb.replace(0, 5, "Hello!"));
//反转字符串
System.out.print(strb.reverse());
//删除字符串
System.out.print(strb.deleteCharAt(6));
System.out.print(strb.delete(2, 5));