小白学习笔记之字符串处理
原以为字符串是简单到不能再简单的东西,但是一个项目中的字符串判定却碰了壁,影响了项目进度,说明还是掌握的不熟练,不全面,所以整理所学,加深记忆。
1.声明字符串
在java语言中字符串必须包含在一对双引号之间,例如
String str;
2.创建字符串
在java语言中讲字符串当做对象来处理,例如
//通过构造方法来创建
char a[]={'A','B','C','D'};
Strig str=new String(a);
//或者引用字符串常量来创建字符串变量
String str="ABCD";
3.连接字符串,可以对多个字符串进行连接,也可以使字符串与其它数据类型进行连接,例如
//1.两个字符串进行连接
String s1=new String("hello");
String s2=new String("word");
String s=s1+""+s2;
System.out.println(s);
//2.字符串与其它数据类型连接,会将这些数据直接转换成字符串,ps:这些数据会自动调用toString()方法,转换成字符串,参与连接。
int year=2016;
String str="今年是";
System.out.println(str+year);
4.获取字符串长度
String str="hello word";
int size=str.length();
//长度返回值赋值给int变量size,返回值为10,长度是包含空格的。
5.字符串查找
String str="hello word";
int size=str.indexOf("o");
//indexOf()方法返回搜索的字符“o”首次在str中出现的位置。如果没有检索到,返回-1。
int size1=str.lastIndexOf("o");
//lastIndexOf()方法将最后一次出现“o”的位置返回。如果没有检索到,返回-1。
6.获取指定位置的字符
String str="hello word";
char mychar=str.charAt(5);
//将指定下标位置的字符返回,这里是下标为5。
7.获取子字符串
String str="hello word";
String substr=str.substring(3);
/**
str.substring(int beginIndex)
从beginIndex位置开始直到字符串结尾截取,此处结果为lo word
*/
String substr1=str.substring(0,3);
/**tr.substring(int beginIndex,int endIndex)
从beginIndex位置开始直到endIndex位置截取,此处结果为hel
ps:可以理解为[0,3)范围*/
8.去除空格
str.trim()
//返回字符串副本,忽略前导空格和尾部空格。
9.字符串替换
String str="hello word";
String newwstr=str.replace("h","H");
/**
str.replace(char oldChar,char newChar)
将旧内容替换为新内容,此处结果为Hello word
ps:如果oldChar出现多次会全部替换掉,同时此方法是区分大小写
*/
10.判断字符串的开始和结尾
String str="hello word";
boolean b1=str.startsWith("h");
boolean b2=str.endSWith("d");
/**
str.startsWith(String prefix)
判断当前字符串对象的前缀是否是指定的字符串
str.endsWith(String suffix)
判断当前字符串对象的后缀是否是指定的字符串
ps:返回值都是boolean类型
*/
后续继续整理