运行java实例
1.public class StringCompareEmp{
public static void main(String args[]){
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;//将str的值赋给objstr
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) ); //忽略大小写
System.out.println( str.compareTo(objStr.toString()));
}
}
compareTo()方法的实现思路:两个字符数组依次从前开始比较,如果对象位置出现字符不同则返回两个字符的编码之差,后面的字符不再比较;如果两个字符数组的长度不一样,并且较短的数组和较长数组所有对应位置的字符都相同,则返回两个数组的长度之差。
2.
public class Test{
public static void main(String args[]){
Integer x = 5;
System.out.println(x.compareTo(3));//1
System.out.println(x.compareTo(5));//0
System.out.println(x.compareTo(8));//-1
}
}
如果指定的数与参数相等返回0。
如果指定的数小于参数返回 -1。
如果指定的数大于参数返回 1。
3.
string类
int compareTo(Object o)//object对象
int compareTo(String anotherString)//string对象
public class Test {
public static void main(String args[]) {
String str1 = "Strings";
String str2 = "Strings";
String str3 = "Strings123";
int result = str1.compareTo( str2 );//0
System.out.println(result);
result = str2.compareTo( str3 );//-3
System.out.println(result);
result = str3.compareTo( str1 );//3
System.out.println(result);
}
}
4.
通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置.
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Runoob";
int lastIndex = strOrig.lastIndexOf("Runoob");
if(lastIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
}
}
}
5.
public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) );//Wello World
System.out.println( str.replaceFirst("He", "Wa") );//Wallo World
System.out.println( str.replaceAll("He", "Ha") );//Hallo World
}
}
6.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);
}
}
7.使用了String 类的indexOf()方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0如果不存在返回-1.
public class SearchStringEmp {
public static void main(String[] args) {
String strOrig = "Google Runoob Taobao";
int intIndex = strOrig.indexOf("Runoob");
if(intIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串位置 " + intIndex);
}
}
}
浙公网安备 33010602011771号