目录
3.3.3 compare ToIgnoreCase( )方法
3.5.1 String[] split(String regex)
3.5.2 String[] split(String regex, int limit)
3.6.1 String substring(int beginIndex)
3.6.2 String substring(int beginIndex, int endIndex)
编辑四.StringBuilder和StringBuffer
4.2 setCharAt(int index, char ch)
4.5 ensureCapacity(int mininmumCapacity)
4.6 insert(int offset, String str)
4.8 replace(int start, int end, String str)
一. String类的概念
在Java中 String类是用于表示和操作字符串的类,字符串是Java中常用的数据类型,用于存储文本信息,并且String类中提供了许多方法用来执各种字符串操作,那么我们随着下文来学习一下常见的方法。
1.1 String类的特性
1. 不可变性:
String 对象是不可变的,一旦创建了 String 对象,其里面的内容就不能被修改,对 String的任何操作实际上都是创建了一个新的 String 对象。
注意:不能修改指的是:String对象的内容不能修改,而指向String对象的引用是可以修改的
2. 常量池的概念
字符串常量池是Java中用于存储字符串字面量的内存区域,为了节省内存,Java使用字符常量池来存储字符串字面量,当创建相同的字符串字面量时,它们会引用常量池中的同一个对象,从而降低程序内存的开销。
二. 字符串的构造方式
1. 使用字符串字面量构造
public class Test {
public static void main(String[] args) {
String s1 = "hello world"; //直接使用字符串字面量进行构造
System.out.println(s1);
}
}
2. 通过new关键字创建一个String对象
public class Test {
public static void main(String[] args) {
String s2 = new String("hello world");//通过new关键字创建对象
System.out.println(s2);
}
}
3.使用字符数组进行构造
public class Test {
public static void main(String[] args) {
char[] str = {'h','e','l','l','o','w','o','r','l','d'};
String s3 = new String(str); //使用字符数组进行构造
System.out.println(s3);
}
}
以上就是最常见的最常见的字符串构造方式。
三. 常用方法
3.1 字符串查找
(1)char charAt( int index)
public class Test {
public static void main(String[] args) {
String str="hello world";
char ch=str.charAt(1);
System.out.println(ch);//e
}
}
如果输入一个不合法的下标位置,就会发生报错:
(2)int indexOf( int ch)
public class Test {
public static void main(String[] args) {
String str="hello world";
int n=str.indexOf('l');
System.out.println(n); //2
}
}
(3)int indexOf(int ch, int fromIndex)
public class Test {
public static void main(String[] args) {
String str="hello world";
int n=str.indexOf('o',6);
//从下标为6的位置(w)开始往后查找o的位置,7
System.out.println(n);
}
}
(4)int indexOf(String str)
public class Test {
public static void main(String[] args) {
String str="hello worldwor";
int n=str.indexOf("wor");
// 返回wor第一次出现的位置,没有返回-1,所以返回值为6
System.out.println(n);
}
}
平台声明:以上文章转载于《CSDN》,文章全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,仅作参考。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/2402_86304740/article/details/143365403



相关文章
- C++草原三剑客之一:继承 2025-04-29
- 后端之路——阿里云OSS云存储 2025-04-29
- jdk21下载、安装(Windows、Linux、macOS) 2025-04-29
- 2023第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组(真题&题解)(C++/Java题解) 2025-04-29
- Java【多线程】(8)CAS与JUC组件 2025-04-29
- Android 14 、15动态申请读写权限实现 (Java) 2025-04-29
- 重返JAVA之路——图书管理系统 2025-04-29
- 《深入解析Java synchronized死锁:从可重入锁到哲学家就餐问题》 2025-04-29
- Java【多线程】(8)CAS与JUC组件 2025-04-28
- Android 14 、15动态申请读写权限实现 (Java) 2025-04-28