Java processes strings: find strings, compare strings, and splice strings


foreword

It is often necessary to process strings in programming. The following introduces some commonly used processing methods for strings.


1. String comparison

1.1 Use equals() for comparison, not ==

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2); //true
        System.out.println(s1.equals(s2)); //true
    }
}

Here you will find that both == and equals() are true, but the Java compiler will automatically put all the same strings as an object into the constant pool during compilation, and naturally the references of s1 and s2 are the same.
Another way of writing == will appear false:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1 == s2); //false
        System.out.println(s1.equals(s2)); //true
    }
}

1.2 Ignore case comparison with equalsIgnoreCase()

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1.equals(s2)); //false
        System.out.println(s1.equalsIgnoreCase(s2)); //true
    }
}

2. Search substring contains(), indexOf(), lastIndexOf(), startsWith(), endsWith()

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        "sunshine".contains("sun"); // true
        "sunshine".indexOf("s"); // 0
		"sunshine".lastIndexOf("s"); // 3
		"sunshine".startsWith("sun"); // true
		"sunshine".endsWith("ine"); // true
    }
}

3. Extract substring substring()

grammar:

//beginIndex -- 起始索引(包括), 索引从 0 开始。
public String substring(int beginIndex)
//endIndex -- 结束索引(不包括)。
public String substring(int beginIndex, int endIndex)
public class TestString {
    
    
    public static void main(String[] args) {
    
    
        "sunshine".substring(1); // "unshine"
		"sunshine".substring(3, 7); //"shine"
    }
}

4. Remove the first and last blank characters trim(), stripLeading(), stripTrailing(), strip()

Use the trim() method to remove leading and trailing whitespace characters from a string. Whitespace characters include space, \t, \r, \n:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        "  \tsunshine\r\n ".trim(); // "sunshine"
        "\u3000sunshine\u3000".strip(); // "sunshine"
		" sunshine ".stripLeading(); // "sunshine "
		" sunshine ".stripTrailing(); // " sunshine"
    }
}

5. Determine whether the string is empty isEmpty() and blank string isBlank()

The code is as follows (example):

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        "".isEmpty(); // true,因为字符串长度为0
		"  ".isEmpty(); // false,因为字符串长度不为0
		"  \n".isBlank(); // true,因为只包含空白字符
		" Hello ".isBlank(); // false,因为包含非空白字符
    }
}

6. Replace substring replace(), or regular expression

6.1 replace()

public class TestString {
    
    
    public static void main(String[] args) {
    
    
        String s = "sunsunshine";
		s.replace('s', 'w'); // "wunwunwhine",所有字符's'被替换为'w'
		s.replace("su", "~~"); // "~~n~~nshine",所有子串"su"被替换为"~~"
    }
}

6.2 Using regular expressions:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		String s = "A,,B;C ,D";
		s.replaceAll("[\\,\\;\\s]+", ","); // "A,B,C,D"
    }
}

Seven split string split(), spliced ​​string join()

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		String s = "A,B,C,D";
		//分割字符串
		String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}
		String[] arr = {
    
    "A", "B", "C"};
		//拼接字符串
		String s = String.join("***", arr); // "A***B***C"
    }
}

Eight converted to char[]

String and char[] types can be converted to each other:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		char[] cs = "Hello".toCharArray(); // String -> char[]
		String s = new String(cs); // char[] -> String
    }
}

If the char[] array is modified, the String will not change

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		char[] cs = "Hello".toCharArray(); // String -> char[]
		String s = new String(cs); // char[] -> String
		System.out.println(s);//"Hello"
        cs[0] = 'X';
        System.out.println(s);//"Hello"
    }
}

This is because when creating a new String instance through new String(char[]), it will not directly reference the incoming char[] array, but will make a copy, so modifying the external char[] array will not Affects the char[] array inside the String instance, since these are two different arrays.

Nine efficient string splicing StringBuilder, StringJoiner and join()

9.1 StringBuilder

The Java compiler does special processing for String, so that we can directly use + to splice strings.

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		String s = "";
		for (int i = 0; i < 1000; i++) {
    
    
    		s = s + "," + i;
		}
    }
}

But it is not recommended to use this way, because each cycle will create a new string object, and then throw away the old string. This will generate a lot of temporary objects, which not only wastes memory, but also affects GC efficiency.

In order to concatenate strings efficiently, it is recommended to use StringBuilder, which is a mutable object that can pre-allocate buffers, so that new temporary objects will not be created when new characters are added.

StringBuilder can also use chain operations, because the append() method will return this, so that it can continuously call other methods of itself.

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		StringBuilder sb = new StringBuilder(1024);
		for (int i = 0; i < 100; i++) {
    
    
	   		sb.append(',');
	    	sb.append(i);
		}
		String s = sb.toString();
		//使用链式操作
		StringBuilder sb1 = new StringBuilder(1024);
		sb1.append("Mr ")
			.append("Zhang")
          	.append("!")
          	.insert(0, "Hello, ");
        //"Hello, Mr Zhang!"
        System.out.println(sb.toString());
    }
}

9.2 StringJoiner

In actual development, we often need to splice multiple pieces of data and return them. This is to splice arrays with separators. At this time, it is more convenient to use StringJoiner.
Let's first look at how to deal with it with StringBuilder:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		StringBuilder sb = new StringBuilder(1024);
		String[] msgs= {
    
    "第1条处理成功", "第2条处理成功", "第3条处理失败"};
		sb.append("处理情况:");
        for (String msg: msgs) {
    
    
            sb.append(msg).append(",");
        }
        // 注意去掉最后的",":
        sb.delete(sb.length() - 1, sb.length());
        sb.append("!");
        //处理情况:第1条处理成功,第2条处理成功,第3条处理失败!
        System.out.println(sb.toString());
    }
}

Let's take a look at how to deal with StringJoiner:

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		StringJoiner sj = new StringJoiner(",");
		String[] msgs= {
    
    "第1条处理成功", "第2条处理成功", "第3条处理失败"};
        for (String msg: msgs) {
    
    
            sj.add(msg);
        }
        //第1条处理成功,第2条处理成功,第3条处理失败
        System.out.println(sj.toString());
        //还可以添加头和尾
        StringJoiner sjoiner = new StringJoiner(",","处理情况:","!");
        for (String msg: msgs) {
    
    
            sjoiner.add(msg);
        }
        //处理情况:第1条处理成功,第2条处理成功,第3条处理失败!
        System.out.println(sjoiner.toString());
    }
}

This is very convenient for concatenating strings.

9.3 Use join() when you don't need to specify "start" and "end"

In addition, String also provides a static method join(), which has been mentioned above when splicing strings. This method is suitable for use when there is no need to specify the "beginning" and "end".

public class TestString {
    
    
    public static void main(String[] args) {
    
    
		String[] arr = {
    
    "A", "B", "C"};
		//拼接字符串
		String s = String.join("***", arr); // "A***B***C"
		String[] msgs= {
    
    "第1条处理成功", "第2条处理成功", "第3条处理失败"};
		//第1条处理成功,第2条处理成功,第3条处理失败
		String msg = String.join(",", msgs); 
    }
}

Summarize

This article introduces some common methods for processing strings. In actual development, we often encounter the need to process strings, which will make our development more efficient.

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/127874130