jdk 1.3 中的 Java 拆分

标签 java split

我在 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/

相关文章:

java - 将句子拆分为两个单词并作为键、值存储在 HashMap 中

java - 将字符串分成三分之一

javascript - 将字符串拆分成对、三元组、四元组和 on (ngrams)?

javascript - 使用 grunt 将一个函数的多个部分连接并 uglify 到一个文件中

Powershell:从 $file.Fullname 中减去 $pwd

java - 安卓工作室java.lang.NoClassDefFoundError : android. support.v4.app.NavUtilsJB

java - Mallet 主题建模 API - 如何确定所需的间隔数或最适合优化的间隔数?

java - 我无法在 Selenium 中将 Java 的解决方案重写为 C#

java - Windows 和 Linux 中 InetSocketAddress#getHostName 对于 "127.0.0.1"的不同行为

java - Android - 无法从最终的 GestureDetectorCompat 继承