java字符串

1 字符串创建的三+一种方法

1         String s = new String();
2         String s2 = new String(new char[]{'a','b','c'});
3         String s3 = new String(new byte[]{97,98,99});
4         String s4 = "abc";
5         System.out.println("s"+s);
6         System.out.println("s2"+s2);
7         System.out.println("s3"+s3);
8         System.out.println("s34"+s4);

2 字符串在底层是字节数组

直接“”创建出的字符串在常量池中

字符串是不可变变量

3 字符串方法:

  直接用 == 是地址值的比较

1         String s2 = new String(new char[]{'a','b','c'});
2         String s3 = new String(new byte[]{97,98,99});
3         String s4 = "abc";
4         String s5="abc";
5         System.out.println(s2==s3); //false
6         System.out.println(s2==s4); //false
7         System.out.println(s5==s4);  //true

字符串比较方法  equals()  equalsIgnoreCase()

1         String s2 = new String(new char[]{'a','b','c'});
2         String s3 = new String(new byte[]{97,98,99});
3         String s4 = "abc";
4         String s5="Abc";
5         System.out.println(s2.equals(s3)); 
6         System.out.println(s4.equalsIgnoreCase(s5));

 

 

字符串获取相关方法
public int length():获取字符串当中含有的字符个数,拿到字符串长度。
public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。
public char charAt(int index):获取指定索引位置的单个字符。(索引从0开始。)
public int indexOf(String str):查找参数字符串在本字符串当中首次出现的索引位置,如果没有返回-1值。

1         String s="afdsfdsfsdf";
2         System.out.println(s.length());
3         System.out.println(s.concat("////"));
4         System.out.println(s.charAt(0));
5         System.out.println(s.indexOf("ds"));

 


字符串截取方法
public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。
public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。

1         String s="afdsfdsfsdf";
2         System.out.println(s.substring(2));
3         System.out.println(s.substring(2,5));

 


字符串转换方法
public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。

1         String s="afdsfdsfsdf";
2         System.out.println(s.toCharArray());
3         System.out.println(s.getBytes());
4         System.out.println(s.replace("a","#"));

 


字符串的分割方法
public String[] split(String regex):按照参数的规则,将字符串切分成为若干部分。
注意事项:
split方法的参数其实是一个“正则表达式” 需要转义
今天要注意:如果按照英文句点“.”进行切分,必须写"\\."(两个反斜杠)

posted @ 2021-03-20 16:06  jmdm  阅读(46)  评论(0)    收藏  举报