1:判断两字符串是否相等
public class Hello {
public static void main(String[] args) {
String s1 = new String("hello,beauty!");
String s2 = new String("hello,lisa!");
if (s1.equals(s2)) {
System.out.println("相同");
} else {
System.out.println("不相同");
}
}
}
/*不相同
exit
Process finished with exit code 0
*/
注意事项
(1)不能使用if(s1==s2)
(2)中英文字符只占一个字符
2:字典序判断两字符串是否相等
例如:一个班有30个学生,按字母顺序进行排序。
String s1=“liming”;
String s2=“lilei”;
if(s1.compareTo(s2)<0)
System.out.println(s1+“位于前面”);
else
System.out.println(s2+"位于前面“);
注意:忽略大小写得比较,用compareToIgnoreCase()
3:字符串得格式化
(1)String s=String.format(“姓名:%s,年龄:%d,身高:%.2f”,“Lisa”,18,1.72)
(2)注意事项:
String.format()是一个静态方法
(3)格式化时: %s对应字符串
%d对应整数
%.2f表示显示两个小数
4:查找indexOf
如果有这个字串,则返回位置索引;否则返回-1
String s=“China is a great country”;
int pos=s.indexOf(“great”);
if(pos<0)
{System.out.println(“not found”);
}
package my;
public class Hello {
public static void main(String[] args) {
String filename = "test.mp4";
if (filename.endsWith(".mp4")) {
System.out.println("支持该视频格式");
}
}
}
/*支持该视频格式
Process finished with exit code 0*/