加载中...

字符串

1.不使用new的方式

String prompt = "Hello World";

从字符串池中查找,如果字符串池中没有,则在字符串池中创建

字符串一旦创建,任何方法都不能修改其内容

①对于对象的所有操作都不能改变原来对象

②在对象的整个生存周期内固定不变

2.使用new的方式

String prompt=new String("Hello World");每次创建一个新的对象

字符串拼接(+或concat)

String a="test";

String b="3";

String c=a+b; //test3

String d="test"+"3" //test3

String e=a+2+1; //test21

String f=a+(2+1); //test3

String g=a.concat("3"); //test3

字符串比较(==和equals)

==

比较两个对象的地址是否相同;//这里是说等不等的问题

equals()

比较当前对象的值是否和另一字符串一致;

//这里是比较不同字符串例如int和String

equalsIgnoreCase

不区分大小写比较两个比较当前对象的值是否和另一字符串一致

//例如验证码的比对

例子:

String a = "test";

String b = "test";

String c = new String("test");

String d = "te" + "st";

String e = "te";

String f = "st";

String g = e + f;

System.out.println(a == b);(true)

System.out.println(a.equals(b));(true)

System.out.println(c == a);(false)

System.out.println(a.equals(c));(true)

System.out.println(d == a);(true)

System.out.println(a.equals(d));(true)

System.out.println(g == a);(false)

System.out.println(a.equals(g));(true)

StringBuffer和StringBuilder

优点:

专门用来拼接字符串的类

拼接过程中不创建新对象

节省内存,效率更高

区别:

StringBuilder:非线程安全

作为局部变量时使用

StringBuffer:线程安全

作为类成员变量时使用

操作:

append/insert 添加或插入一段

delete 删除一段

reverse 反转

字符操作(toCharArray和charAt)

charAt();取值是0 - length()-1;

获取字符串的长度是方法length() 数组是属性

posted @ 2022-09-20 21:57  说句话吧  阅读(24)  评论(0)    收藏  举报