欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > String类

String类

2024/10/23 23:19:59 来源:https://blog.csdn.net/2301_80634989/article/details/140045140  浏览:    关键词:String类

学习String类,主要就是学习String类中包含的一些方法。

一、String类中的常用方法:

1. String类的定义方法:

1. String s1 = "Hello";

2. String s2 = new String("Hello");

3. char[] array = {'h', 'e', 'l', 'l', 'o'};

    String s3 = new String(array); 

注意:第一类构造方法和其他两类有所差异,s1会先去检查字符串常量池中有没有,没有的话才会创建一个abc的对象,举个例子:

public static void main(String[] args) {String s1 = "abc";String s2 = "abc";System.out.println(s1 == s2);}

运行结果:

true

2. String对象的比较:

2.1 "=="比较:

“==”比较的是引用中的地址,判断引用的是否是同一个对象。

public static void main(String[] args) {String s1 = "abc";String s2 = new String("abc");String s3 = s1;System.out.println(s1 == s2);//falseSystem.out.println(s1 == s3);//ture}

运行结果: 

false
true

2.2 boolean equals(Object anObject) 方法: 

equals方法是用来比较引用对象是否相同的方法。

public static void main(String[] args) {String s1 = "abc";String s2 = "def";String s3 = new String("abc");System.out.println(s1.equals(s2));//falseSystem.out.println(s1.equals(s3));//true}

运行结果:

false
true

2.3 int compareTo(String s) 方法: 

compareTo方法用来比较字符串大小,从零下标开始对字符依次进行比较,当两个字符不同或到达字符串末尾,返回差值。

public static void main(String[] args) {String s1 = "abc";String s2 = "acc";System.out.println(s1.compareTo(s2));}

运行结果:

-1

2.4 int compareToIgnoreCase(String str) 方法:

与compareTo比较方式相同,只不过会忽略字符的大小写。

public static void main(String[] args) {String s1 = "abc";String s2 = "ABC";System.out.println(s1.compareToIgnoreCase(s2));}

运行结果: 

0

3. 字符串查找:

3.1 charAt方法:

char charAt(int index):

返回index位置上字符,如果index为负数或者越界,抛出 IndexOutOfBoundsException异常。

public static void main(String[] args) {String s = "abcdef";char ch = s.charAt(2);System.out.println(ch);}

 运行结果:

c

3.2 int indexOf(int ch):

返回ch第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.indexOf('d');System.out.println(pos);}

运行结果:

3

3.3 int indexOf(int ch, int fromIndex):

从fromIndex位置开始找ch第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.indexOf('d', 4);System.out.println(pos);}

运行结果:

-1

3.4 int indexOf(String str):

返回str第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.indexOf("bc");System.out.println(pos);}

运行结果:

1

3.5 int indexOf(String str, int fromIndex):

从fromIndex位置开始找str第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.indexOf("bc", 2);System.out.println(pos);}

运行结果:

-1

3.6 int lastIndexOf(int ch):

从后往前找,返回ch第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.lastIndexOf('d');System.out.println(pos);}

运行结果:

3

3.7 int lastIndexOf(int ch, int fromIndex):

从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返 回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.lastIndexOf('d', 2);System.out.println(pos);}

运行结果:

-1

3.8 int lastIndexOf(String str):

从后往前找,返回str第一次出现的位置,没有返回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.lastIndexOf("cd");System.out.println(pos);}

运行结果:

2

 3.9 int lastIndexOf(String str, int fromIndex):

从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返 回-1。

public static void main(String[] args) {String s = "abcdef";int pos = s.lastIndexOf("cd", 1);System.out.println(pos);}

运行结果:

-1

4. 转化:

4.1 数值和字符串转化:

valueOf()方法:

public static void main(String[] args) {String s1 = String.valueOf(1234);String s2 = String.valueOf(12.34);String s3 = String.valueOf(true);String s4 = String.valueOf(new Student("wyh", 12));System.out.println(s1);System.out.println(s2);System.out.println(s3);System.out.println(s4);}
1234
12.34
true
Student{name='wyh', age=12}

4.2 字 符 串 转 数 组:

toCharArray()方法:

public static void main(String[] args) {String s = "hello";char[] chars = s.toCharArray();System.out.println(Arrays.toString(chars));}

运行结果:

[h, e, l, l, o]

 4.3 大 小 写 转 换:

toUpperCase()和toLowerCase()方法:
public static void main(String[] args) {String s = "hello";String s1 = s.toUpperCase();System.out.println(s1);String s2 = s1.toLowerCase();System.out.println(s2);}

运行结果:

HELLO
hello

4.4 格 式 化:

format()方法:
public static void main(String[] args) {int year = 2024;int month = 6;int day = 29;String s = String.format("%02d-%02d-%02d", year, month, day);System.out.println(s);}

运行结果:

2024-06-29

5. 字 符 串 替 换:

5.1 String replaceAll(String regex, String replacement):

替换所有的指定内容。

public static void main(String[] args) {String s = "abcdefg";String s1 = s.replaceAll("c", "cc");System.out.println(s1);}

运行结果:

abccdefg

5.2 String replaceFirst(String regex, String replacement):

替换首个内容。

public static void main(String[] args) {String s = "abcdecfg";String s1 = s.replaceFirst("c", "cc");System.out.println(s1);}

运行结果:

abccdecfg

6. 字符串拆分:

6.1 String[] split(String regex):

将字符串全部拆分,用字符串数组接受。

public static void main(String[] args) {String s1 = "hello-world";System.out.println(Arrays.toString(s1.split("-")));}

运行结果:

[hello, world]

6.2 String[] split(String regex, int limit):

将字符串以指定的格式,拆分为limit组。

public static void main(String[] args) {String s1 = "he-llo-wor-ld";System.out.println(Arrays.toString(s1.split("-", 3)));}

运行结果:

[he, llo, wor-ld]

有些特殊字符作为分割符可能无法正确切分, 需要加上转义。(转义字符为“\\”)

例1. 

public static void main(String[] args) {String s1 = "he.llo.wor.ld";System.out.println(Arrays.toString(s1.split("\\.")));}

运行结果:

[he, llo, wor, ld]

例2. 

public static void main(String[] args) {String s1 = "he\\llo\\wor\\ld";System.out.println(Arrays.toString(s1.split("\\\\")));}

运行结果:

[he, llo, wor, ld]

补充: 

1. 字符"|","*","+"都得加上转义字符,前面加上 "\\" .

2. 而如果是 "\" ,那么就得写成 "\\\\" .

3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.

public static void main(String[] args) {String s1 = "he&llo=wor.ld";System.out.println(Arrays.toString(s1.split("&|=|\\.")));}

运行结果:

[he, llo, wor, ld]

7. 字符串截取:

从一个完整的字符串之中截取出部分内容。

7.1 String substring(int beginIndex):

从指定索引截取到结尾。

public static void main(String[] args) {String s = "abcdefghi";System.out.println(s.substring(3));}

运行结果:

defghi

7.2 String substring(int beginIndex, int endIndex):

截取部分内容(左闭右开)。

public static void main(String[] args) {String s = "abcdefghi";System.out.println(s.substring(3, 6));}

运行结果:

def

8. 其他操作方法:

去掉字符串中的左右空格,保留中间空格。

public static void main(String[] args) {String s = " a b c ";System.out.println(s.trim());}

运行结果:

a b c

二、String的不可变性:

在演示上面所有的String类的方法时,其实都不是对字符串本身进行修改,都是创建了一个新的对象。

当我们点进String这个类时会发现:

这里面的private就是它为什么具有不可变性的原因了,我们没有修改这个成员变量的权限。 

如果每次修改字符串都需要创建一个新的对象,效率会大大降低,所以我们在使用String的时候应该尽量避免对字符串的修改。

三、StringBuilder和StringBuffer:

运行一段代码:

public static void main(String[] args) {long start = System.currentTimeMillis();//获得程序开始的时间String s1 = "";for (int i = 0; i < 10000; i++) {s1 += i;}long end = System.currentTimeMillis();//获得程序结束的时间System.out.println(end -  start);//打印开始与结束这段代码的运行时间,单位为毫秒。start = System.currentTimeMillis();//获得程序开始的时间StringBuffer sbf = new StringBuffer("");for (int i = 0; i < 10000; i++) {sbf.append(i);}end = System.currentTimeMillis();//获得程序结束的时间System.out.println(end -  start);//打印开始与结束这段代码的运行时间,单位为毫秒。start = System.currentTimeMillis();//获得程序开始的时间StringBuilder sbd = new StringBuilder();for (int i = 0; i < 10000; i++) {sbd.append(i);}end = System.currentTimeMillis();//获得程序结束的时间System.out.println(end -  start);//打印开始与结束这段代码的运行时间,单位为毫秒。}

运行结果:

62
1
1

观察发现,当使用StringBuilder和StringBuffer时字符串的拼接效率会更快,这是因为StringBuilder和StringBuffer在拼接字符串的时候不需要创建新的对象,直接就是在字符串本身进行修改。

StringBuilder和StringBuffer之间的差别:

StringBuilder是单线程,StringBuffer是多线程,可以保证线程安全,但不意味着StringBuffer一定比StringBuilder好,因为在单线程情况下使用StringBuffer也是对资源的一种浪费。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com