Recently I encountered a small problem in the project. A string is divided into an array, similar to String str="aaa,bbb,ccc"; and then "," is used as the separator to divide it into an array. Use What method is used to achieve this?
The first method:
You may immediately think of using the split() method. It is the most convenient to use the split() method, but its efficiency is relatively low
Second method:
Use the more efficient StringTokenizer class to split the string. The StringTokenizer class is a tool class provided in the JDK specifically for processing string splitting into substrings. Its constructor is as follows:
public StringTokenizer(String str,String delim)
str is the string to be split and delim is the split symbol. When a StringTokenizer object is generated, it can be obtained through its nextToken() method. For the next split string, you can use the hasMoreTokens() method to know whether there are more substrings that need to be processed. This method is more efficient than the first one.
The third method:
Use two methods of String—indexOf() and subString(). subString() uses time-for-space technology, so its execution efficiency is relatively low. Soon, just deal with the memory overflow problem, but use it boldly. The indexOf() function is a very fast execution method.
The prototype is as follows:
public int indexOf(int ch) It returns the position of the specified character in the String object. As follows:
Example:
"ab&&2"以&分割成"ab" "2" String tmp = "ab&&2"; String splitStr = null; int j = tmp.indexOf("&"); // 找分隔符的位置 splitStr = tmp.substring(0, j); // 找到分隔符,截取子字符串 tmp = tmp.substring(j + 2); // 剩下需要处理的字符串 System.out.println(splitStr); System.out.println(tmp); ab 2
The above three methods (summary) of java string segmentation are all the content shared by the editor. I hope it can To give you a reference, I also hope that everyone will support the PHP Chinese website.
For more articles related to the three methods of java string segmentation, please pay attention to the PHP Chinese website!