我在 intelliJ 中使用 jdk 1.3 时遇到 String[] t = Words.split("_");
错误
Error:(133, 51) java: cannot find symbol
symbol: method split(java.lang.String)
location: variable words of type java.lang.String
我必须使用这个SDK,因为项目很旧,我尝试了jdk 1.4,但有很多其他错误,然后我决定将上面的代码替换为可以使用jdk 1.3编译的代码。
它的作用是什么?
最佳答案
下面的代码似乎对我来说工作得很好。
但是,我假设您需要分割的分隔符只是一个字符。
public static void main(String[] args){
String string = ",alpha,beta,gamma,,delta";
String[] wordsSplit = splitByDelimiter(string, ",");
for(int i=0; i<wordsSplit.length; i++){
System.out.println("-"+wordsSplit[i]+"-");
}
}
public static String[] splitByDelimiter(String fullString, String delimiter){
// Calculate number of words
int index = 0;
int[] delimiterIndices = new int[fullString.length()];
int wordCount = 0;
do{
if(delimiter.equals(fullString.charAt(index)+"")){
delimiterIndices[wordCount++] = index;
}
index++;
} while(index < fullString.length());
// Correction for strings not ending in a delimiter
if(!fullString.endsWith(delimiter)){
delimiterIndices[wordCount++] = fullString.length();
}
// Now create the words array
String words[] = new String[wordCount];
int startIndex = 0;
int endIndex = 0;
for(int i=0; i<wordCount; i++){
endIndex = delimiterIndices[i];
words[i] = fullString.substring(startIndex, endIndex);
startIndex = endIndex+1;
}
return words;
}
替代解决方案:
public static ArrayList splitByDelimiter(String fullString, String delimiter){
fullString += delimiter; //
ArrayList words = new ArrayList();
int startIndex = 0;
int endIndex = fullString.indexOf(delimiter); //returns first occurence
do{
words.add(fullString.substring(startIndex, endIndex));
startIndex = endIndex+1;
endIndex = fullString.indexOf(delimiter, startIndex);
} while(endIndex != -1);
return words;
}
关于jdk 1.3 中的 Java 拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542768/