菜鸟教程中的实例
1.Java 实例 - 字符串比较
代码:
public class StringCompareEmp {
public static void main(String arrgs[]) {
String str="hello World";//创建字符串str
String antherString="hello world";//创建新的字符串antherString
Object objStr=str;//将String str转换为Object,将调用toString()
System.out.println(str.compareTo(antherString));//返回字符串中第一个字母ASCII的差值
System.out.println(str.compareToIgnoreCase(antherString));//忽略大小写返回差值
System.out.println(str.compareTo(objStr.toString()));//按字典顺序返回差值
}
}
运行结果:
2.查找字符串最后一次出现的位置
代码:
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Runoob";//创建新的字符串strOrig
int lastIndex = strOrig.lastIndexOf("Runoob");//确定指定字符在strOrig中最后一次出现处的索引
if(lastIndex==-1) {
System.out.println("没有找到字符串 Runoob");//在strOrig中没有Runoob
}else {
System.out.println("Runoob 字符串最后出现的位置:"+lastIndex);//在字符串中有Runoob
}
}
}
运行结果:
Runoob 字符串最后出现的位置: 19
3.删除字符串中的一个字符
代码:
public class Main {
public static void main(String args[]) {
String str="this is Java";//创建新的字符串str
System.out.println(removeCharAt(str,3));//删除第三个字符
}
public static String removeCharAt(String s,int pos) {
return s.substring(0,pos)+s.substring(pos+1);//返回从0位置但poe位置的字符串+起始位置pos+1到字符串末尾的字符串
}
}
运行结果:
thi is Java