package com.shujia.day11;
/*
String类的其他功能:
替换功能
String replace(char old,char new) 将字符串中所有的旧字符使用新字符进行替换,返回新的字符串
String replace(String old,String new) 将字符串中所有的旧字符串使用新字符串进行替换,返回新的字符串
去除字符串两空格
String trim()
按字典顺序比较两个字符串
int compareTo(String str) 比较两个字符串中的内容是否相同,当结果是0的时候,说明比较的两个内容相同
int compareToIgnoreCase(String str) //自己测试
*/
public class StringDemo7 {
public static void main(String[] args) {
String s1 = "今天ajava的天气是java非炎热,每走一java步都出java汗!";
//String replace(char old,char new) 将字符串中所有的旧字符使用新字符进行替换,返回新的字符串
String res1 = s1.replace('a', '_');
System.out.println("s1: "+s1);
System.out.println("res1: "+res1);
System.out.println("----------------------------------------------");
//String replace(String old,String new) 将字符串中所有的旧字符串使用新字符串进行替换,返回新的字符串
String res2 = s1.replace("java", "hadoop");
System.out.println("s1: "+s1);
System.out.println("res2: "+res2);
System.out.println("----------------------------------------------");
//String trim() 去除字符串两边的空白字符
String s2 = " hello world ";
String res3 = s2.trim();
System.out.println("s2: "+s2);
System.out.println("res3: "+res3);
// String res4 = s2.replace(" ", "");
// System.out.println("res4: "+res4);
System.out.println("----------------------------------------------");
//int compareTo(String str) 比较两个字符串中的内容是否相同,当结果是0的时候,说明比较的两个内容相同
String s3 = "hello";
String s4 = "world";
System.out.println(s3.compareTo(s4)); // -15
String s5 = "hel";
System.out.println(s3.compareTo(s5)); // 2
String s6 = "hello";
System.out.println(s3.compareTo(s6)); // 0
}
}
int compareTo(String str)方法的源码
//s3.compareTo(s4)
class String{
public int compareTo(String anotherString) {
// value -- s3 -- "hello"
// anotherString -- s4 -- "hel"
int len1 = value.length; // 5
int len2 = anotherString.value.length; // 3
int lim = Math.min(len1, len2); // 3
char[] v1 = value; // {'h','e','l','l','o'}
char[] v2 = anotherString.value; // {'h','e','l'}
int k = 0;
while (k < lim) {
char c1 = v1[k]; // 'h' 'e' 'l'
char c2 = v2[k]; // 'h' 'e' 'l'
if (c1 != c2) {
return c1 - c2; // 104 - 119 = -15
}
k++;
}
return len1 - len2; // 5-3=2
}
}
标签:String,int,System,空格,println,day11,字符串,out
From: https://www.cnblogs.com/qiwei-bigdata/p/18349740