String 常用函数

时间:2024-07-09 19:05:44
  • 判断字符串是否包含指定字符str.contains("string");
  • 查找指定字符索引str.indexOf("s"');
  • 查找最后出现的字符索引str.iLastIndexOf("s");
  • 分割字符串注意函数名称是substring不是subString
  • 索引方式遍历字符串char a = str.charAt(i);
  • toLowerCase()转换为小写
  • toUperCase()转换为大写
  • byte[] b = getBytes()返回字节数组
  • String.valueOf()2将任何基本数据类型转换为String类型
  • trim()去除前后的空格
  • split()分割字符串,返回字符数组String[] array = name.split("\,")注意使用转意;
  • startWith(),endWith()以什么开头以什么结尾
String str = "qwer";
String s1 = str.substring(0,indexOf('e'));// s1 = "qw";切割从开始索引到结束索引减1的字符串
String s2 = str.substring(indexOf('e'));// s2 = "er";
  • 字符串转换为字符数组str.toCharArray();
  • StringBuffer 添加内容是append函数
  • HashSet添加内容是add函数

    字符串都是常亮,存在于常量区,相同的字符串不会出现第二次,新建 String 对象时,如果常量区有相同的字符串,会在堆区生成新对象的引用,所以新生成的对象虽然字符和原来的对象相同,但是地址还是不同的

在方法参数传递中只有值传递,基本数据类型参数是直接复制值,引用数据类型是复制引用,所以方法可以修改引用数据类型的值

Java程序设计语言总是采用按值调用。也就是说,方法得到的是所有参数值的一个拷贝,也就是说,方法不能修改传递给它的任何参数变量的内容。

new的时候会产生新的地址,并指向新的对象

		String s = "abc";
String s1 = s;
String s2 = "abc";
String s3 = new String("abc");
System.out.println(s == s1); // true
System.out.println(s == s2); // true
System.out.println(s == s3); // false
s = "efg";
System.out.println(s1); // abc
int a = 1;
int b = a;
a = 2;
System.out.println(b); // 1
Person p = new Person();
Person p1 = p;
p = new Students();
System.out.println(p); // object.Students@15db9742
System.out.println(p1);// object.Person@6d06d69c
1 String s1 = "Hello";
2 String s2 = "Hello";
3 String s3 = "Hel" + "lo";
4 String s4 = "Hel" + new String("lo");
5 String s5 = new String("Hello");
6 String s6 = s5.intern();
7 String s7 = "H";
8 String s8 = "ello";
9 String s9 = s7 + s8;
10
11 System.out.println(s1 == s2); // true
12 System.out.println(s1 == s3); // true
13 System.out.println(s1 == s4); // false
14 System.out.println(s1 == s9); // false
15 System.out.println(s4 == s5); // false
16 System.out.println(s1 == s6); // true