10 common problems and solutions to the String class (String manipulation) in Java

  • 2020-04-01 03:17:03
  • OfStack

This article introduces the 10 most common String problems in Java:

1. String comparison, "==" or equals()?
In simple terms, "==" determines whether two references are to the same memory address (the same physical object).
Equals determines whether the values of two strings are equal.
Unless you want to determine whether two string references are the same object, you should always use the equals() method.
You'll understand this better if you understand String Interning

2. Why is using char[] better than String for sensitive information?
A String is an immutable object, meaning that once created, the entire object cannot be changed.
The programmer can explicitly change the array of characters, so sensitive information (such as passwords) is not easily exposed elsewhere (as long as you set 0 to char[] when you're done).

3. Use String as a case condition in the switch statement?
Starting with JDK7, this is fine, and by the way, neither Java 6 nor previous versions support it.


//Only available in Java 7 and later!  
switch (str.toLowerCase()) {  
      case "a":  
           value = 1;  
           break;  
      case "b":  
           value = 2;  
           break;  
}  


4. Convert String to number
Use Long for very large Numbers, the code is as follows

int age = Integer.parseInt("10");  
long id = Long.parseLong("190"); //If the value can be large.


5. How to split a string by whitespace
The String received by the split() method of the String is parsed as a regular expression,
"\s" represents white space characters such as space "", TAB TAB "\t", newline "\n", and enter "\r".
The compiler also does literal transcoding when parsing the source code, so "\\s" is required.

String[] strArray = aString.split("\s+");  


6. The substring ()   How is the method handled internally?
In JDK6, the substring() method still shares the original char[] array and constructs a "new" String by offset and length.
To substring() get a newly created object, use the following method:

String sub = str.substring(start, end) + "";  

Of course in Java 7,substring() creates a new char[] array instead of sharing it.
To learn more, see :  The substring() method and its differences in JDK6 and JDK7

7. String vs StringBuilder vs StringBuffer
StringBuilder is mutable, so you can modify the internal values after creation.
Stringbuffers are synchronous and therefore thread-safe, but less efficient.

8. How do I repeatedly concatenate the same string?
Scenario 1: use the StringUtils utility class of the Apache Commons Lang library.


String str = "abcd";  
String repeated = StringUtils.repeat(str,3);//abcdabcdabcd  

Scheme 2:
Use StringBuilder construction. More flexible.

String src = "name";  
int len = src.length();  
int repeat = 5;  
StringBuilder builder = new StringBuilder(len * repeat);  
for(int i=0; i<repeat; i++){  
  builder.append(src);  
}  
String dst = builder.toString();  


9. How do I convert a String to a date?

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
String str = "2013-11-07";  
Date date = format.parse(str);  
System.out.println(format.format(date));//2013-11-07  


10. How to count the number of occurrences of a character?
Also using the Apache Commons Lang library stringutilss   Class:

int n = StringUtils.countMatches("11112222", "1");  
System.out.println(n);  


Related articles: