String类
字符串的创建
String s1 = "hello";
String s2 = s1; // 相同引用
直接赋值的字符串存放在公共池
String s3 = new String("hello");
new 创建的字符串对象存放在堆上。
需要注意的是,String对象的值是不可变的。如果要对字符串做很多修改,要使用 StringBuffer & StringBuilder 类。
字符串的长度
int num = str.length();
// 返回int类型的字符串长度值。
连接字符串
- String类提供了连接两个字符串的方法
string1.concat(string2)
。字符串常量也可以使用。 - 使用
+
完成字符串的连接。
需要在完成操作后使用一个字符串变量来接收。
String的方法
方法 | 描述 |
---|---|
charAt() | 返回指定索引处的 char值 |
copyValueOf(char[] data) | 返回指定数组中表示该字符序列的 String |
copyValueOf(char[] data,int offset, int count) | 返回指定数组中表示该字符序列的String |
startsWith(String prefix) | 测试此字符串是否以指定的前缀开始 |
startsWith(String prefix, int toffset) | 测试此序列从指定索引开始的子字符串是否以指定前缀开始 |
endsWith(String suffix) | 判断此字符串是否以指定后缀结束 |
equals(Object x) | 将此字符串与指定的对象比较 |
equalsIgnoreCase(string str) | 将此字符串与另一个字符串比较,不考虑大小写 |
hashCode() | 返回此字符串的哈希码 |
indexOf(int ch) | 返回指定字符在此字符串中第一次出现出的索引 |
indexOf(int ch,int fromIndex) | 从指定位置开始检索,返回在此字符串中第一次出现指定字符出的索引 |
indexOf(String str) | 指定字符串检索 |
indexOf(String str,int fromIndex) | 从指定位置检索,检索字符串 |
lastIndexOf(int ch) | 返回指定字符在此字符串中最后一次出现处的索引 |
lastIndexOf(int ch,int fromIndex) | 从指定的索引处开始反向搜索 |
length() | 返回数组长度 |
matches(String regex) | 返回boolean值,告知是否匹配给定的正则表达式 |
replace(char oldChar,char newChar) | 返回新字符串,通过用 newChar 替换此字符串中所有的 oldChar 得到 |
subSequence(int begin,int end) | 返回一个新字符序列,从指定的开始和结束位置截取原字符串 |
substring(int begin) | 从指定位置截取,返回一个新字符串 |
substring(int begin,int end) | 从指定位置开始和结束,截取源字符串,并返回新字符串 |
toCharArray() | 将字符串转为一个新的字符数组 |
toLowerCase() | 将字符串中的字母都转为小写 |
toUpperCase() | 将字符串中的所有字母都转为大写 |
toString() | 返回此对象本身 |
trim() | 返回字符串的空白,去除前部空白和尾部空白 |
isEmpty() | 判断字符串是否为空 |