Java 字符串

字符串常量池

常量池:是堆内存的存储区域, 当创建一个String对象时,假如此字符串值已经存在于常量池中,则不会创建一个新的对象,而是引用已经存在的对象
!字符串一旦初始化就不可被改变:字符串常量池里面的值不可改变,并非字符串的引用不可改变

		String s1 = "hello";    // 加入常量池
		s1 += "world";          // 加入常量池,s1指向新生成的字符串,并且hello还在常量池中
		System.out.println(s1);
		String s2 = "hello";    // 并不加入常量池即可直接引用

字符串判断

		String s1 = "hello world";
                
                // 判断等串
		s1.equals("hello world");//区分大小写
		s1.equalsIgnoreCase("HELLO WORLD");//不区分大小写

                // 判断包含
		s1.contains("hello"); //true

                // 判断开始/结束
		s1.startsWith("hello"); //以hello开始
		s1.endsWith("world");  //以world结束

                // 判空
		s1.isEmpty();//判断是否是空串

字符串比较

== 是比较引用是否相等, Object.equal()判断他们是否是值相等

                //比较两个值一样的字符串
                new String("test").equals("test") // --> true 
                /比较字符串值一样,但不同的对象
                new String("test") == "test" // --> false 
                //比较字符串值一样,但不同的对象
                new String("test") == new String("test") // --> false 

		String s1 = "abc";
		String s2 = "abC";
		System.out.println(s1.compareTo(s2));//比较字符串,不同字符相减操作
		System.out.println(s1.compareToIgnoreCase(s2));//同上不区分大小写

字符串获取

		String str = "你好世界heloworld";
		
                //返回字符串给定索引字符
		System.out.println(str.charAt(0));    //'你'

		//返回字符串第一次出现给定字符的位置,不存在返回-1
		System.out.println(str.indexOf("l"));

		System.out.println(str.indexOf("l",str.indexOf("l") + 1) );//从第一次出现的位置继续向后查找,包含当前位置
		System.out.println(str.lastIndexOf("l"));//返回字符串最后一次出现给定字符的位置
		
                //字符串截取,包头
		System.out.println(str.substring(4));
		System.out.println(str.substring(4, 8));//包头不包尾

字符串切割

		String nameSz[] = name.split(",");// 根据分隔符分隔字符串
		System.out.println(nameSz[0].toString());

		String address = "  Anhui,Suzhou  ";
		System.out.println(address.trim());// 去首尾空格

字符串替换

		String name="xyg,sll,sjl";
		
		//替换功能
		String newName = name.replace(",", "||");//替换所有
		System.out.println(newName);
		System.out.println(name.replaceAll(",", " "));// 替换所有
		System.out.println(name.replaceFirst(",", " "));// 替换第一个

字符串转换

                String name = "xyg,ssl,smt";

		// 将字符串转换成字节数组
		byte[] b = name.getBytes();
		System.out.println(b);

		// 将字符串转换为字符数组
		char[] chName = name.toCharArray();
		System.out.println("chName = " + chName[0]);

		// 将字符数组转换为字符串
		String strName = String.copyValueOf(chName);  //1.copyValueOf
		strName = new String(chName);  //2.构造
		strName = String.valueOf(chName); // 3.valueOf

		// 将任意基本类型转换为字符串类型
		float f = (float) 3.1415926;
		strName = String.valueOf(f);
		System.out.println(strName);

		// 全转小写
		System.out.println(name.toLowerCase());

		// 全转大写
		System.out.println(name.toUpperCase());

StringBuffer 字符串缓存区类

采用缓存区机制,其值可改变

构造

		// 方式1
		// strBuf还是指向原来的对象
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("world");
		// 实际字符个数
		System.out.println(strBuf.length());
		// StringBuffer容量,默认16
		System.out.println(strBuf.capacity());
		System.out.println("===================");
		
		// 方式2
		StringBuffer strBuf2 = new StringBuffer(100);//指定容量
		System.out.println(strBuf2.length());
		System.out.println(strBuf2.capacity());
		System.out.println("===================");
		
		// 方式3
		StringBuffer strBuf3 = new StringBuffer("helloworld");
		System.out.println(strBuf3.length());
		System.out.println(strBuf3.capacity());
		System.out.println("===================");

StringBuffer的功能

		StringBuffer sb1 = new StringBuffer();
		
		// 追加
		sb1.append("hello");
		sb1.append(3.34).append(true).append(30); // 任意基本类型追加为String
		System.out.println(sb1);

		// 插入
		sb1.insert(5, "world"); // 指定位置插入
		System.out.println(sb1);
		
		// 删除
		sb1.deleteCharAt(0); // 删除指定位置字符
		System.out.println(sb1);
		sb1.delete(0, 4);//指定开始结束位置删除,左闭右开
		System.out.println(sb1);
		
		// 反转
		sb1.reverse();
		System.out.println(sb1);

StringBuilder

效率高 不同步数据 线程不安全,适用于单线程下在字符缓冲区进行大量操作的情况

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		sb.append("hello");
		change(sb); // 传递的是引用,所以值改变了
		System.out.println(sb);
	}

	private static void change(StringBuilder sb) {
		sb.append("world");
	}

String、StringBuffer、StringBuilder之间的转换

	public static void main(String[] args) {
		String str = "helloString";
		StringBuffer sbf = new StringBuffer("helloBuffer");
		StringBuilder sbd = new StringBuilder("helloBuilder");
		
		StringToBuffer(str);
		BufferToString(sbf);
	}

	private static void BufferToString(StringBuffer sbf) {
		//1.String的构造方法
		String str = new String(sbf);
		//2.toString方法
		sbf.toString();
	}

	private static void StringToBuffer(String str) {
		//1.构造器
		StringBuffer sbf = new StringBuffer(str);
		//2.append方法
		sbf.append(str);
	}

实例

每隔4位数字插入一个空格

        /**
            1234 5678 8908 65
        */
        StringBuffer buffer = new StringBuffer(number1);
        int length = buffer.length();
        // 每隔4位数字插入一个空格
        for (int cnt = 4;cnt < length;cnt+=4){
            buffer.insert(cnt, ' ');
            cnt++; //插入空格时,需要偏移一位
            length++; //插入时长度也会改变
        }
原文地址:https://www.cnblogs.com/xiongyungang/p/12672156.html