Java常用字符串方法小结
下面是对字符串操作的代码小总结。大部分是String类的操作方法,需要的朋友可以参考下
publicclassStudyString{
publicstaticvoidmain(String[]ergs){
//字符串的声明与赋值
Stringname="蔡宇飞";
Stringhisname=newString("小明");
System.out.println(name+"和"+hisname+"是好朋友");
//字符串基本操作
//获取字符串的长度
//字符串名.length()返回字符的个数
Stringhello="helloworld!";
intlength=hello.length();
System.out.println(hello+"的长度是"+length);
//字符串连接
//String类提供的concat()方法
//字符串1.concat(字符串2)返回值是一个字符串
Stringtwoname=name.concat(hisname);
System.out.println(twoname);
//字符串比较
//String提供的equals()方法,返回值为boolean类型。两个字符串中每个字符完全一致时才为turn.否则为false
//字符串1.equals(字符串2)
Stringstr1="fuck";
Stringstr2="FUCK";
if(str1.equals(str2))
System.out.println("相同");
else
System.out.println("不同");
//String还提供了equalsIgnoreCase()方法,这个与上面的区别是不区分字母的大小写。返回值同样为boolean类型
//字符串1.equalsIgnoreCase(字符串2)
if(str1.equalsIgnoreCase(str2))
System.out.println("相同");
else
System.out.println("不同");
//字符串截取
//从字符串中截取一部分作为新的字符串,String类提供的substring来实现
//字符串.substring(开始位置);或者字符串.substring(开始位置,结束位置);
//第一种是从开始位置直到结束,第二种从开始位置到结束位置.
Stringmy="mynameiscaiyufei,IloveJavaandPython.";
Stringlove=my.substring(20);
Stringmyname=my.substring(11,19);
System.out.println(love);
System.out.println(myname);
//字符串查找
//在一个字符串中查找另一个字符串,String类提供了indexOf方法来实现
//字符串1.indexOf(字符串2)或字符串1.indexOf(字符串2,开始位置)
intlovenum=my.indexOf(love);
intmynamenum=my.indexOf(myname);
System.out.println(lovenum);
System.out.println(mynamenum);
//字符串替换
//用一个新字符去替换字符串中指定的所有字符String类提供了replace方法实现这种替换
//字符串1.replance(被替换字符,替换字符)
charI_='I';
charm_='M';
System.out.println(love.replace(I_,m_));//MloveJavaandPython.
//字符串与字符数组
//将字符数组作为构造函数的参数直接转换成字符串
char[]helloArray={'h','e','l','l','o'};
StringhelloString=newString(helloArray);
System.out.println(helloString);
//将字符串转为字符数组
//toCharArray()方法
char[]Array=helloString.toCharArray();
for(inti=0;i
上面代码学习的朋友可以参考下