字符串是一个特殊的对象
字符串一旦初始化就不可以被改变
String s = "abc";//"常量区中没有,存放在常量区"
s = "abcd";//创建"abcd"并且放在常量池里,
//然后s指向这个新的字符串,原来的字符串并没有进行改变。
字符串定义的方式
- 字符串定义的第一种方式
明确常量池的特点,池中没有就调用 ,池中有就直接用
String s = "abc";//"常量区中没有,存放在常量区"
String s1 = "abc";//常量中已经有"abc",所以不再创建
System.out.println(s == s1);//true,所以这两个变量名指向的是同一个对象
- 字符串定义的第二种方式
String s = "abc";//"常量区中没有,存放在常量区"
String s1 = new String("abc");//这个定义方式和常量池没有半点关系,因此s1
System.out.println(s == s1);//false,所以这两个变量名指向的不是同一个对象
System.out.print(s.equals(s1));//true 因为equals重写了object类中的equals,使得比较的是两个字符串的内容
字符串中的方法:
构造方法:
1.可以传入char数组,将char数组转化为字符串
char[] c= {'h','e','l','l','o'};
String s2=new String(c);
System.out.println(s2);//hello
String s3=new String(c,1,3);
System.out.println(s3);//ell
2.可以传入byte数组,打印的是ASII码中的字符‘
//传入数组,可以直接转化成字符串
byte[] arr= {97,66,67,68};
String s1=new String(arr);
System.out.println(s1);//aBCD
一般方法:
- 获取
获取字符串中字符的个数
String s="hello,world ";
System.out.println(s.length());//12
根据位置获取字符
String s="hello,world ";
System.out.println(s.charAt(0));//h
根据字符获取第一次出现的位置:
indexOf()从前往后找
lastIndexOf()从后往前找
String s="hello,world ";
System.out.println(s.indexOf('w'));//从0开始找
System.out.println(s.indexOf('w',7));//-1 从指定位置寻找’
获取字符串中的一部分字符串
String s="hello,world ";
System.out.println(s.substring(3,7));//lo,w
- 转换
将字符串变成字符串数组–切割
String s="hello,world ";
String[] arr= s.split(",");//利用“,”分隔
System.out.println(arr[0]);//hello
System.out.println(Arrays.deepToString(arr));//[hello, world ]
将字符串转化成字符数组
String s="hello,world ";
char[] c=s.toCharArray();
System.out.println(Arrays.toString(c));//[h, e, l, l, o, ,, w, o, r, l, d, ]
将字符串中的字母转成大小写
toUpperCase();
toLowerCase();
替换字符,和替换字符串
String replace(char oldch,char newch);
如果没有找到oldch,则不改变
String replaceAll(char oldch,char newch);
trim():去除字符串两端所有空格
String s=" hello,world -";
System.out.println(s.replace('h','a'));// aello,world -
System.out.println(s);// hello,world -
System.out.println(s.trim());//hello,world -
连接
String s="hello";
System.out.println(s.concat(",world"));//hello,world
-
判断
两个字符串内容是否相同:
equals(String s)
equalsIgnoreCase:忽略大小写对字符串进行比较
字符串是否包含某个字符串:
contains(String s)
字符串是否以指定字符串开头,是否以指定字符串结尾:
endWith(string s)
startWith(string s ) -
比较
基于字典顺序比较两个字符串谁大谁小
int compareTo(string a,string b)
练习
1.给定一个字符串数组,按照字典顺序进行从小到达的排序
[“nba”,“abc”,“cba”,“zz”,“qq”,“haha”]
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i].compareTo(arr[j])>0)//
{
swap(arr,i,j);
}
}
2.一個子串在字符串中出現的次數
private static int subString(String s,String substring) {
int count =0;
int index=0;
index=s.indexOf(substring);
while(index!=-1)
{
count++;
index=s.indexOf(substring, index+substring.length());
}
return count;
}