zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java字符串详解(深入浅出)

JAVA 详解 字符串 深入浅出
2023-06-13 09:15:03 时间

今天先来仔细分析下java中字符串,字符串我们是我们最开始接触的类,它也是java中的常用类,十分重要,掌握他对我们很重要!!!!!!!

String 类:代表字符串。 Java 程序中的所有字符串字面值(如 "abc" )都作 为此类的实例实现。

String 是一个 final 类,代表 不 可变的字符序列 。

字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改。

String 对象的字符内容是存储在一个字符数组 value[] 中的

下面是内存分析: 

如果是new String(“Tom”)则为flase 

String使用陷阱

 String s1 = "a";

说明:在字符串常量池中创建了一个字面量为"a"的字符串。

 s1 = s1 + "b";

说明:实际上原来的“a”字符串对象已经丢弃了,现在在堆空间中产生了一个字符

串s1+"b"(也就是"ab")。如果多次执行这些改变串内容的操作,会导致大量副本

字符串对象存留在内存中,降低效率。如果这样的操作放到循环中,会极大影响

程序的性能。

String s2 = "ab";

说明:直接在字符串常量池中创建一个字面量为"ab"的字符串。

String s3 = "a" + "b";

说明:s3指向字符串常量池中已经创建的"ab"的字符串。

String s4 = s1.intern();

说明:堆空间的s1对象在调用intern()之后,会将常量池中已经存在的"ab"字符串

赋值给s4。

字符串相关的类:String常用方法

public class text1
{
	public static void main(String[] args) {
		String str = "12hello34world5java7891mysql456";
		//把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉
		String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
		System.out.println(string);
	}
}

输出结果:hello,world,java,mysql

public class text1
{
	public static void main(String[] args) {
		String str1 = "12345";
		//判断str字符串中是否全部有数字组成,即有1-n个数字组成
		boolean matches = str1.matches("\\d+");
		System.out.println(matches);
		String tel = "0571-4534289";
		//判断这是否是一个杭州的固定电话
		boolean result = tel.matches("0571-\\d{7,8}");
		System.out.println(result);
	}
}

输出结果: true true

public class text1
{
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "中";
		System.out.println(str.getBytes("ISO8859-1").length);// -128~127
		System.out.println(str.getBytes("GBK").length);
		System.out.println(str.getBytes("UTF-8").length);
		System.out.println(new String(str.getBytes("ISO8859-1"), 
		"ISO8859-1"));// 乱码,表示不了中文
		System.out.println(new String(str.getBytes("GBK"), "GBK"));
		System.out.println(new String(str.getBytes("UTF-8"), "UTF-8"));
	}
}

 输出结果:

 字符串相关的类:StringBuffer

 字符串相关的类:StringBuilder

public class text1
{
	public static void main(String[] args) {
		String str = null;
		StringBuffer sb = new StringBuffer();
		sb.append(str);
		System.out.println(sb.length());//
		System.out.println(sb);//
		StringBuffer sb1 = new StringBuffer(str);
		System.out.println(sb1);//
	}
}

 输出结果: 4 null Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null     at java.base/java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:105)     at java.base/java.lang.StringBuffer.<init>(StringBuffer.java:158)     at text1.main(text1.java:1313)

 这就是今天的全部!