关于java中字符串方法的应用
比较两个字符串是否相等
永远记得我的初中老师和我说过,听会了,并不是真正的学会了。只有把自己学的东西讲给别人听,让别人听懂,才是真的学会了。
比较两个字符串是否相等,使用equals方法。实现代码如下。
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="abcda";
String str2="Abcda";
String str3="abcda";
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
}
}
运行结果如下,我们可以看出equals方法是区分大小写的。
忽略差字符大小写的字符串比较方法
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="abcda";
String str2="Abcda";
String str3="abcda";
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.equalsIgnoreCase(str3));
}
}
运行结果如下图,我们可以看出equalsIgnoreCase方法是去不区别大小写的。
判段字符串是否为空
判断字符串是否为空值 (非null)
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="";
String str2="aa";
System.out.println(str1.isEmpty());
System.out.println(str2.isEmpty());
}
}
运行结果如图
字符串的索引
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="abvcvdAa";
String str2="bc";
System.out.println(str1.indexOf("a")); //从头开始查,查询到第一个后就停止向后查询
System.out.print("str2字符出现在str1中的位置为");
System.out.println(str1.indexOf(str2));
System.out.print("当判断的字符不属于查询字串时的值为:");
System.out.println(str1.indexOf("h")); //如果所查字符不再字符串里,返回-1
System.out.print("从第四个开始,查询后边的a字母的的值为");
System.out.println(str1.indexOf("v",3)); //从规定的下标后边查询
System.out.println(str1.indexOf(65));// 65为A的Ascll码
}
}
运行如下图。我们要知道字符串的下标是从0开始的
求字符串的长度
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="abvcvdAa";
System.out.println(str1.length()); //得到字符串str1的长度
}
}
运行如下图
字符串字符替换
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="abvcvdAa";
System.out.println(str1.replace('a', 'g'));
}
}
输入结果
判断字符串的开头
public class test {
public static void main(String[] args) {
String str="www.daixin.com";
System.out.println(str.startsWith("www"));//判断是不是以www开头
System.out.println(str.endsWith("com")); //判断字符串是不是以com结尾
}
}
运行结果