java split函数
实例一
* stringhelper.split("1-2-3", "-");<br>
* result: {"1","-","2","-","3"}<br>
* stringhelper.split("-1--2-", "-");<br>
* result: {"","-","1","-","","-","2","-",""}<br>
* stringhelper.split("123", "");<br>
* result: {"123"}<br>
* stringhelper.split("1-2--3---4----5", "--");<br>
* result: {"1-2","--","3","--","-4","--","","--","5"}<br>
public static string[] split(string s, string delimiter){
int delimiterlength;
// the next statement has the side effect of throwing a null pointer
// exception if s is null.
int stringlength = s.length();
if (delimiter == null || (delimiterlength = delimiter.length()) == 0){
return new string[] {s};
}
int count;
int start;
int end;// scan s and count the tokens.
count = 0;
start = 0;
while((end = s.indexof(delimiter, start)) != -1){
count++;
start = end + delimiterlength;
}
count++;// allocate an array to return the tokens,
// we now know how big it should be
string[] result = new string[count];// scan s again, but this time pick out the tokens
count = 0;
start = 0;
while((end = s.indexof(delimiter, start)) != -1){
result[count] = (s.substring(start, end));
count++;
start = end + delimiterlength;
}
end = stringlength;
result[count] = s.substring(start, end);return (result);
}
实例二
public static string[] splitincludedelimiters(string s, string delimiter){
int delimiterlength;
int stringlength = s.length();
if (delimiter == null || (delimiterlength = delimiter.length()) == 0){
return new string[] {s};
}
int count;
int start;
int end;// scan s and count the tokens.
count = 0;
start = 0;
while((end = s.indexof(delimiter, start)) != -1){
count+=2;
start = end + delimiterlength;
}
count++;// allocate an array to return the tokens,
// we now know how big it should be
string[] result = new string[count];// scan s again, but this time pick out the tokens
count = 0;
start = 0;
while((end = s.indexof(delimiter, start)) != -1){
result[count] = (s.substring(start, end));
count++;
result[count] = delimiter;
count++;
start = end + delimiterlength;
}
end = stringlength;
result[count] = s.substring(start, end);return (result);
}}
补充:Jsp教程,Java基础