String类
String类形容的是文本字符串序列。
特点:
- 字符串是常量,它的值在创立之后不能再修改。
- 字符串的内容一旦发生了变化,那么马上会创立一个新的对象。
注意:字符串的内容不适宜频繁修改,由于一旦修改马上就会创立一个新的对象。假如需要频繁修改的字符串内容,建议使用字符串缓冲类。
一、字符串的创立
创立String类的对象的两种方式:
- “”直接赋值法
- new关键字法
public class Demo { public static void main(String[] args) { String str1 = "hcx"; String str2 = "hcx"; String str3 = new String("hcx"); String str4 = new String("hcx"); System.out.println(str1==str2);//true System.out.println(str1==str3);//false System.out.println(str3==str4);//false System.out.println(str3.equals(str4));//true }}- String str = “hcx”:
这种方式创立字符串的时候,jvm首先会检查字符串常量池中能否存在该字符串对象:
假如已经存在,那么就不会在字符串常量池中再创立了,直接返回该字符串常量池中的内存地址;
假如该字符串不存在于字符串常量池中,那么就会在字符串常量池中先创立该字符串对象,而后再返回。
- new String(“hcx”):
这种方式会创立字符串的时候,jvm首先会检查字符串常量池中能否存在”hcx”字符串,假如已经存在,则不会在字符串常量池中创立了;
假如还没有存在,那么就会在字符串常量池中创立”hcx”字符串对象,而后还会去到堆内存中再创立一份字符串的对象,把字符串常量池中的”hcx”字符串内容拷贝至内存中的字符串对象,而后返回堆内存中字符串对象的内存地址。
string内存分析图.png
二、String类常用方法
1.构造方法
- String() 创立一个空内容 的字符串对象。
- String(byte[] bytes) 使用一个字节数组构建一个字符串对象
- String(byte[] bytes, int offset, int length)
bytes : 要解码的数组
offset: 指定从数组中那个索引值开始解码。
length: 要解码多个元素。 - String(char[] value) 使用一个字符数组构建一个字符串。
- String(char[] value, int offset, int count) 使用一个字符数组构建一个字符串, 指定开始的索引值,与使用字符个数。
- String(int[] codePoints,int offset,int count)
- String(String original)
String str = new String();byte[] buf = {97,98,99};str = new String(buf); //使用一个字节数组构建一个字符串对象str = new String(buf,1,2); //使用一个字节数组构建一个字符串对象,指定开始解码的索引值和解码的个数。char[] arr = {'明','天','是','春','节'};str = new String(arr); //使用字符数组构建一个字符串str = new String(arr,3,2);int[] buf2 = {65,66,67};str = new String(buf2,0,3);str = new String("abc");System.out.println("字符串的内容:"+str);2.获取方法
- int length() 获取字符串的长度
- char charAt(int index) 获取特定位置的字符 (角标越界)
- int indexOf(String str) 获取特定字符的位置(overload)
- int lastIndexOf(int ch) 获取最后一个字符的位置
示例:
package com.hcx.string;public class Demo1 { public static void main(String[] args) { String str = "hello world"; System.out.println("length():"+str.length());//11 //第一次出现字符l的下标位置 System.out.println("indexOf():"+str.indexOf("l"));//2 //最后一次出现字符l的下标位置 System.out.println("lastIndexOf():"+str.lastIndexOf("l"));//9 //不存在该字符时,返回-1 System.out.println("indexOf():"+str.indexOf("p"));//-1 //获取指定下标位置的字母 System.out.println("chartAt():"+str.charAt(1));//e //假如位置越界,则抛出异常 System.out.println("charAt():"+str.charAt(12));// java.lang.StringIndexOutOfBoundsException }}3.判断方法
- boolean endsWith(String str) 能否以指定字符结束
- boolean isEmpty()能否长度为0 如:“” null V1.6
- boolean contains(CharSequences) 能否包含指定序列 应用:搜索
- boolean equals(Object anObject) 能否相等
- boolean equalsIgnoreCase(String anotherString) 忽略大小写能否相等
示例:
public class Demo2 { public static void main(String[] args) { String str = " "; System.out.println("length():"+str.length());//1 System.out.println("isEmpty():"+str.isEmpty());//false str = "hello java world"; System.out.println("contains():"+str.contains("java"));//true System.out.println("abc".equals("abc"));//true //String类重写了equals方法,比较的是String对象存储的字符内容 System.out.println(new String("abc").equals(new String("abc")));//true System.out.println(new String("abc").equals(new String("Abc")));//false System.out.println(new String("abc").equalsIgnoreCase(new String("Abc")));//true str="Demo2.java"; System.out.println("endsWith():"+str.endsWith(".java"));//true }}4.转换方法
- String(char[] value) 将字符数组转换为字符串
- String(char[] value, int offset, int count)
- Static String valueOf(char[] data)
- static String valueOf(char[] data, int offset, int count)
- char[] toCharArray() 将字符串转换为字符数组
示例:
package com.hcx.string;public class Demo3 { public static void main(String[] args) { String str = new String(new char[]{'h','e','l','l','o'}); System.out.println(str);//hello char[] chars = str.toCharArray(); for(int i=0;i<chars.length;i++){ System.out.println(chars[i]);//h e l l o } byte[] bs = new byte[]{97,98,99}; String str1 = new String(bs); System.out.println(str1);//abc byte[] bytes = str.getBytes(); for(int i=0;i<bytes.length;i++){ System.out.println(bytes[i]);//104 101 108 108 111 } }}5.其余方法
- String replace(char oldChar, char newChar) 替换
- String[] split(String regex) 切割
- String substring(int beginIndex)
- String substring(int beginIndex, int endIndex)截取字串
- String toUpperCase() 转大写
- String toLowerCase() 转小写
- String trim() 去除空格
①手动实现trim:
package com.hcx.string;public class Demo { public static void main(String[] args) { String trim = trim(" hello world "); System.out.println(trim);//hello world } // 定义一个去除字符串两边空格的函数 public static String trim(String str) { // 1、定义求字串需要的起始索引变量 int start = 0; int end = str.length() - 1; // 2. for循环遍历字符串对象的每一个字符 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { start++; } else { break; } } System.out.println(start); for (; end < str.length() && end >= 0;) { if (str.charAt(end) == ' ') { end--; } else { break; } } System.out.println(end); // 3. 求子串 if (start < end) { return str.substring(start, (end + 1)); } else { return "_"; } }}②获取文件名 D:\WorkSpaces\Demo.java
public static String getFileName2(String path) { return path.substring(path.lastIndexOf("\\") + 1); }③将字符串逆序输出
// 将字符串对象中存储的字符逆序输出 public static String reaverseString(String src) { // 1. 将字符串转换为字符数组 char chs[] = src.toCharArray(); // 2. 循环交换 for (int start = 0, end = chs.length - 1; start < end; start++, end--) { // 3. 数据交换 char temp = chs[end]; chs[end] = chs[start]; chs[start] = temp; } // 4. 将字符数组转换为字符串 return new String(chs); }④计算子串出现的次数
public static int getCount(String src, String tag) { // 1. 定义索引变量和统计个数的变量 int index = 0; int count = 0; // 2. 写循环判断 while ((index = src.indexOf(tag)) != -1) // jackjava { // 3. 求字串 System.out.println(src); src = src.substring(index + tag.length()); // index 4 + 4 = 8 System.out.print(src.length() + " : " + index + " : " + tag.length()); // 4. 累加 count++; } return count; }