The first method I used most of the split split after the end, divided into different arrays, and then get what you want
the second method is rarely seen.
The third type is used in two parts.
....
string replaces the last obtained string has a/n/p, cannot be converted to a number, and later used "2/n/p". Replace ("/n/p", "") replaced .
There are three methods for string segmentation, as follows:
1. Split with Split () method, split the substring into an array, and then processed.
The sample code is as follows:
public class Splittest {
/**
* @param args
* @author Colin
*/
public static void Main (string[] args) {
String str= "I love Dannie";//define String
String[] array= new STRING[10];
Array=str.split ("");
for (String A:array) {
System.out.println (A + "");
}
}
}
2. Use the StringTokenizer class to operate
The sample code is as follows:
Import Java.util.StringTokenizer;
public class Stringtokenizertest {
/**
* @author Colin
* @return NULL
*/
public static void Main (string[] args) {
String str = new String ("I love Dannie,and i miss her");//define a string
StringTokenizer token = new StringTokenizer (str, ",")://By Space and comma intercept
string[] Array = new string[10];//defines an array of strings
int i = 0;
while (Token.hasmoretokens ()) {
Array[i] = Token.nexttoken ()//To put the split substring into an array
i++;
}
for (int j = 0; J < Array.Length; J + +) {
System.out.print (Array[j] + "");/Traversal output array
}
}
}
3. Use the IndexOf () method to locate, and then use SUBSTRING () to intercept, and then operation.
The sample code is as follows:
public class Fengestring {
/**
* @param args
* @author Colin
*/
public static void Main (string[] args) {
String str = "I love Dannie";
string[] array = new string[10];//definition array
String temp = str;//defines a string variable, assigns str to him, keeps the STR string unchanged
/*
* The first for loop is used to split the string
* Find the location of the space, and then intercept, when the search to finally find no space, the IndexOf () method will return the value of 1, indicating that it could not be found.
*/
for (int i = 0; i < Array.Length; i++) {
int index = Temp.indexof ("");//Where to find spaces
System.out.println ("index=" + index);
if (index = = 1) {
Array[i] = temp;//When no space is found, the last string is left, no segmentation is required, directly assigned to the array, and then the break jumps out of the loop.
Break
}
Array[i] = temp.substring (0, index);
temp = temp.substring (index + 1);
System.out.println ("temp=" + temp);
}
System.out.println ("---------------------------");
/*
* Force in Java for loop output string in array
*/
for (String A:array) {
System.out.print (A + "");
}
System.out.println ();
System.out.println ("---------------------------");
/*
* General for loop output string in array
*/
for (int i = 0; i < Array.Length; i++) {
if ((""). Equals (Array[i]) | | NULL = = Array[i]) {
Break
}
System.out.print (Array[i] + "");
}
}
}