Java比较字符串
示例1 :是同一对象吗
str1和str2的内容一定是一样的! 但是,不是同一字符串对象
打包角色;
公共类测试字符串{
publicstaticvoidmain (字符串[ ] args ) {
String str1='the light ';
stringstr2=newstring(str1;
//==用于确定是否为同一字符串对象
system.out.println(str1==str2;
}
}
示例2 :是否为同一对象-特例
str1=" the light " str3=" the light "
由于编译器通常在每次遇到字符串文字时都会创建新对象,因此在第6行创建新字符串“the light”。 但是,在第7行中,编译器如果发现已经存在立即可用的“the light”,则直接使用,不重复创建
打包角色;
公共类测试字符串{
publicstaticvoidmain (字符串[ ] args ) {
String str1='the light ';
String str3='the light ';
system.out.println(str1==str3;
}
}
例3 :内容相同吗
要使用equals比较字符串的内容,需要大小写匹配的equalsIgnoreCase,并且忽略大小写以确定内容是否匹配
打包角色;
公共类测试字符串{
publicstaticvoidmain (字符串[ ] args ) {
String str1='the light ';
stringstr2=newstring(str1;
String str3=str1.toUpperCase (;
//==用于确定是否为同一字符串对象
system.out.println(str1==str2;
system.out.println(str1.equals ) str2); //完全一样返回true
system.out.println(str1.equals ) str3); //因为大小写不同,所以返回false
system.out.println (str1. equals ignore case ) str3); //忽略大小写比较,返回true
}
}
示例4是否在4 :子字符串中开始或结束
以startsWith //开始,以endsWith //结束
打包角色;
公共类测试字符串{
publicstaticvoidmain (字符串[ ] args ) {
String str1='the light ';
String start='the ';
String end='Ight ';
系统. out.println (str1. starts with (start ) ); //…开头
system.out.println (str1. endswith (end ) ); 以//结尾
}
}
练习:比较字符串
创建长度为100的字符串数组,并在该字符串数组中嵌入长度为2的随机字符,以统计此字符串数组中有多少种重复的字符串(忽略大小写)。
答案:
打包角色;
公共类测试字符串{
publicstaticvoidmain (字符串[ ] args ) {
String[] ss=new String[100];
//初始化
for(intI=0; i ss.length; I ) {
ss[I]=randomstring(2;
}
//打印
for(intI=0; i ss.length; I ) {
system.out.print(ss[I] ';
if(19==I ) )
System.out.println (;
}
for(stringS1:ss ) {
int repeat=0;
for(stringS2:ss ) {
if(S1.equalsignorecase(S2 ) ) }
重复;
if(2==repeat ) {
repeat==2时,查找了不是自己的重复字符串
putintoduplicatedarray(s1;
布雷克;
}
}
}
}
System.out.printf ('合计%d种重复字符串%n ',pos );
if (销售点!=0}{
System.out.println ('分别为) );
for(intI=0; i pos; I ) {
系统. out.print (found duplicated [ I ] ';
}
}
}
staticstring [ ] found duplicated=new string [ 100 ];
静态输入销售点;
隐私保护功能
for(intI=0; i pos; I ) {
if (found duplicated [ I ].equals ignore case (s ) ) ) )
返回;
}
foundDuplicated[pos ]=s;
}
私有状态命令
String pool=' ';
for(shortI='0); i='9'; I ) {
pool=(char ) I;
}
for(shortI='a '; i='z '; I ) {
pool=(char ) I;
}
for(shortI='a '; i='Z '; I ) {
pool=(char ) I;
}
char cs[]=new char[length];
for(intI=0; i cs.length; I ) {
intindex=(int ) ) Math.random ) * pool.length ) );
cs [ I ]=pool.charat (索引;
}
字符串结果=new string (cs;
返回结果;
}
}