java数字字符串⼤⼩⽐较_Java⾃学-数字与字符串⽐较字符串Java ⽐较字符串
⽰例 1 : 是否是同⼀个对象
str1和str2的内容⼀定是⼀样的! 但是,并不是同⼀个字符串对象
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str2 = new String(str1);
//==⽤于判断是否是同⼀个字符串对象
System.out.println( str1  ==  str2);
}
}
⽰例 2 : 是否是同⼀个对象-特例
str1 = “the light”; str3 = “the light”;
⼀般说来,编译器每碰到⼀个字符串的字⾯值,就会创建⼀个新的对象 所以在第6⾏会创建了⼀个新的字符串"the light" 但是在第7⾏,编译器发现已经存在现成的"the light",那么就直接拿来使⽤,⽽没有进⾏重复创建
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str3 = "the light";
System.out.println( str1  ==  str3);
}
}
⽰例 3 : 内容是否相同
使⽤equals进⾏字符串内容的⽐较,必须⼤⼩写⼀致 equalsIgnoreCase,忽略⼤⼩写判断内容是否⼀致
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str2 = new String(str1);
String str3 = UpperCase();
//==⽤于判断是否是同⼀个字符串对象
System.out.println( str1  ==  str2);
System.out.println(str1.equals(str2));//完全⼀样返回true
System.out.println(str1.equals(str3));//⼤⼩写不⼀样,返回false
System.out.println(str1.equalsIgnoreCase(str3));//忽略⼤⼩写的⽐较,返回true
}
}
⽰例 4 : 是否以⼦字符串开始或者结束
startsWith //以…开始 endsWith //以…结束
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String start = "the";
String end = "Ight";
System.out.println(str1.startsWith(start));//以...开始
System.out.dsWith(end));//以...结束
}
}
练习: ⽐较字符串
创建⼀个长度是100的字符串数组 使⽤长度是2的随机字符填充该字符串数组 统计这个字符串数组⾥重复的字符串有多少种(忽略⼤⼩写)答案:
package character;
public class TestString {
public static void main(String[] args) {
java在哪里可以免费自学String[] ss = new String[100];
// 初始化
for (int i = 0; i < ss.length; i++) {
ss[i] = randomString(2);
}
// 打印
for (int i = 0; i < ss.length; i++) {
System.out.print(ss[i] + " ");
if (19 == i % 20)
System.out.println();
}
for (String s1 : ss) {
int repeat = 0;
for (String s2 : ss) {
if (s1.equalsIgnoreCase(s2)) {
repeat++;
if (2 == repeat) {
// 当repeat==2的时候,就打了⼀个⾮⼰的重复字符串putIntoDuplicatedArray(s1);
break;
}
}
}
}
System.out.printf("总共有 %d种重复的字符串%n", pos); if (pos != 0) {
System.out.println("分别是:");
for (int i = 0; i < pos; i++) {
System.out.print(foundDuplicated[i] + " ");
}
}
}
static String[] foundDuplicated = new String[100]; static int pos;
private static void putIntoDuplicatedArray(String s) { for (int i = 0; i < pos; i++){
if (foundDuplicated[i].equalsIgnoreCase(s))
return;
}
foundDuplicated[pos++] = s;
}
private static String randomString(int length) {
String pool = "";
for (short i = '0'; i <= '9'; i++) {
pool += (char) i;
}
for (short i = 'a'; i <= 'z'; i++) {
pool += (char) i;
}
for (short i = 'A'; i <= 'Z'; i++) {
pool += (char) i;
}
char cs[] = new char[length];
for (int i = 0; i < cs.length; i++) {
int index = (int) (Math.random() * pool.length()); cs[i] = pool.charAt(index);
}
String result = new String(cs);
return result;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。