菜鸟教程中的实例1

4.字符串替换

代码:

public class StringReplaceEmp {
public static void main(String args[]) {
String str="Hello World";
System.out.println(str.replace('H','W'));//将字符H替换成字符W
System.out.println(str.replaceFirst("He","Wa"));//将字符串中第一次出现的He替换成Wa
System.out.println(str.replaceAll("He","Ha"));//将字符串中所有的He替换成Ha
}

}

运行结果:

Wello World

Wallo World

Hallo World

5.字符串反转

代码:

public class StringReverseExample {
public static void main(String[] args){
String string="runoob";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("字符串反转前:"+string);//输出反转前的字符串
System.out.println("字符串反转后:"+reverse);//输出反转后的字符串
}

}

运行结果:

字符串反转前:runoob
字符串反转后:boonur

6.字符串搜索(与大小字母无关)

代码:

public class SearchStringEmp {
public static void main(String[] args) {
String str0rig="Goole Runoob Taobao";
int intIndex=str0rig.indexOf("Runoob");//在字符串中查找子字符串出现的位置
if(intIndex==-1) {
System.out.println("没有找到字符串 Runoob");//如果index=-1,说明字符串中没有你想找的字符串

}else {
System.out.println("Runoob 字符串位置"+intIndex);
}
}

}

运行结果:Runoob 字符串位置6

 

 
posted @ 2021-10-22 15:58  好(justice)……  阅读(26)  评论(0编辑  收藏  举报