字符串
String类
一.声明字符串
String a;
二.创建字符串
- 引用字符串常量
String a="我是谁"; - 利用构造方法实例化
利用new关键字创建String对象:
String a=new String("我是谁"); - 利用字符数组实例化:
char[] a={'t','i','m','e'};
String b=new String(a); -
提取字符数组中的一部分创建字符串对象
定义一个字符数组charry,从该字符数组索引3的位置开始,提取两个元素。
char[]charry={'时','间','就','是','金','钱'};
String charry=new String(a,3,2);
Sting.png
连接字符串
一.使用“+”运算符可实现拼接多个字符串的功能。
String a="123";
String b="abc";
String c=a+b;


注意:字符串在计算中的顺序会影响运算结果
String a="1"+2+3+4-------"1234"//碰到字符串后,直接输入后面内容
String a=1+2+3+"4"-------"64"//碰到字符串前,先做运算,后输入内容
String a="1"+(2+3+4)-------"19"//碰到字符串后,先运算括号中的值,后输入内容

提取字符串信息
一.获取字符串长度
str.length();
例如:
String num="123456789";
int size=num.length();
二.获取指定的字符
str.charAt();

结果为g
三.获取子字符串索引位置
1.指定字符串首次的索引位置
a.index();
String str="we are the world";
int size=str.indexOf('e');//size=1
2.从指定位置b开始的第一次出现的索引
a.index(a,b);
//第三次索引不到r时,就返回-1。
3.返回指定子字符串在此字符串最右边出现的索引
a.lastIndexOf(str)
4.返回指定子字符串在此字符串最后一次出现出的索引,从指定的索引开始反向搜索。

四.判断字符串首尾内容
startsWith()判断开始
endsWith()判断结束
这两个方法返回值都是boolean。

五.获取字符数组
将一个字符串转化为一个字符数组
str.toCharArray();

五.判断子字符串是否存在
contains();返回值为boolean类型
String a = "szrfrrgdhjd";
a.contains("g") 里面包含,所以返回true
字符串的操作
一.截取字符串
substring(int beginIndex,int endlndex)
该字符串从beginIndex开始,直到索引 endlndex-1处的字符

二.字符串的替换
-
replace(oldChar, newChar)方法 参数1:要被替换的字符,参数2:替换进去的字符
该方法的作用是替换字符串中所有指定的字符,然后生成一个新的字符串。经过该方法调用以后,原来的字符串不发生改变。例如:
String s = "abcde8fghijk8lmn";
String a = s.replace('8', 'Q');
a的值为"abcdeQfghijkQlmn" -
replaceAll(String regularExpression, String replacement), 替换所有包含的字符串
参数1:要替换的字符串,2,替换进去的字符串
String s = "QQQQabcWWWabcGGGGabc";
String a = s.replaceAll("abc", "PPP");
a的值为"QQQQPPPWWWPPPGGGGPPP" -
如果只替换第一个abc用replaceFirst()
String s = "QQQQabcWWWabcGGGGabc";
String a = s.replaceFirst("abc", "PPP");
a的值为"QQQQPPPWWWabcGGGGabc"
三.字符串分割 -
split()分割字符串返回的是一个String数组
String a = "abcdeAfghijk";
String [] b = a.split("A");//以A作为分割点,将字符串a分割为2个字符串数组分别为
b[0] = "abce";
b[1] = "efghijk" -
如果字符串包含好几个A呢
String a = "abcdeAfghAijk";
String [] b = a.split("A"); //以每个A作为分割点,得到的是
b[0] = "abde";
b[1] = "fgh";
b[2] = "ijk";
分割.png
四.大小写转换
1.toLowerCase()将String转化为小写
2.toUpperCase()将String转化为大写

五.去除空白内容
trim()方法可以返回字符串的副本,忽略首尾的空白

网友评论