首页 > 编程 > Java > 正文

Java常用工具类(二)字符串

2019-11-06 07:53:50
字体:
来源:转载
供稿:网友

字符串

java中字符串的不变性

-String 对象创建后则不能被修改,是不可变的,所谓的修改其实是创建了新的对象,所指向的内存空间不同。 -多次出现的字符串,Java编译器只创建一个。 -一旦一个字符串在内存中创建,则这个字符串将不可改变。如果需要一个可以改变的字符串,我们可以使用 StringBuffer或者StringBuilder。 -每次 new 一个字符串就是产生一个新的对象,即便两个字符串的内容相同,使用 ”==” 比较时也为 ”false” ,如果只需比较内容是否相同,应使用 ”equals()” 方法。

public class test { public static void main(String[] args) { String s1 = "123"; String s2 = "123"; String s3 = new String("123"); String s4 = new String("123"); System.out.PRintln(s1==s2); System.out.println(s1==s3); System.out.println(s4==s3); }}

true false false

String的常用方法

这里写图片描述

-1. 字符串 str 中字符的索引从0开始,范围为 0 到 str.length()-1

-2. 使用 indexOf 进行字符或字符串查找时,如果匹配返回位置索引;如果没有匹配结果,返回 -1

-3. 使用 substring(beginIndex , endIndex) 进行字符串截取时,包括 beginIndex 位置的字符,不包括 endIndex 位置的字符

public class Test2 { public static void main(String[] args) { String s1 = "abcd/efgh"; String s2 = "1234/5678"; String s3 = " 1234/5678"; String s4 = new String("abcd/efgh"); String[] s5; String[] s6; byte[] b1; System.out.println(s1.length()); System.out.println(s1.indexOf("a")); System.out.println(s1.indexOf("abcd")); System.out.println(s1.lastIndexOf("efgh")); System.out.println(s1.lastIndexOf("e")); System.out.println(s1.substring(2)); System.out.println(s1.substring(2,7)); System.out.println(s3.trim()); System.out.println(s1.equals(s4)); System.out.println(s1.toLowerCase()); System.out.println(s1.toUpperCase()); System.out.println(s1.charAt(4)); s5 = s1.split("/"); System.out.println(s5[0]); s6 = s1.split("/",0); System.out.println(s6[0]); b1 = s1.getBytes(); System.out.println(b1[1]); }}

9 0 0 5 5 cd/efgh cd/ef 1234/5678 true abcd/efgh ABCD/EFGH / abcd abcd 98

StringBuilder

-String 类具有是不可变性。StringBuilder可变。 -当频繁操作字符串时,如果用String则会生成很多对象、临时变量,降低系统性能。 - StringBuilder 和StringBuffer ,它们基本相似,不同之处,StringBuffer 是线程安全的,而 StringBuilder 则没有实现线程安全功能,所以性能略高。 -创建内容可变的字符串对象优先考虑StringBuilder。

StringBuilder常用方法

这里写图片描述

public class Test3 { public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder("123213"); String s1 = "123213456456"; System.out.println(stringBuilder.append("456")); System.out.println(stringBuilder.insert(6, "456")); System.out.println(stringBuilder.toString().equals(s1)); System.out.println(stringBuilder.length()); }}

123213456 123213456456 true 12


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表