簡體   English   中英

Java,編寫我自己的拆分字符串方法

[英]Java, writing my own split string method

我需要能夠編寫自己的拆分字符串方法,以便輸入像

String[] test1 = mySplit("ab#cd#efg#", "#");
System.out.println(Arrays.toString(test1));

[ab, #, cd, #, efg, #]打印到控制台。 到目前為止,我已經把它拆分成這樣,但我的方式留下了尷尬的空間,其中 2 個分隔符排成一行,或者分隔符位於輸入的開頭。

public static String[] mySplit(String str, String regex)
{
    String[] storeSplit = new String[str.length()];
    char compare1, compare2;
    int counter = 0;

    //Initializes all the string[] values to "" so when the string
    //and char concatonates, 'null' doesn't appear.
    for(int i=0; i<str.length(); i++) {
        storeSplit[i] = "";
    }

    //Puts the str values into the split array and concatonates until
    //a delimiter is found, then it moves to the next array index.
    for(int i=0; i<str.length(); i++) {
        compare1 = str.charAt(i);
        compare2 = regex.charAt(0);

            if(!(compare1 == compare2)) {
                storeSplit[counter] += ""+str.charAt(i);
            } else {
                counter++;
                storeSplit[counter] = ""+str.charAt(i);
                counter++;
            }
    }
    return storeSplit;
}

當我在 Test main 中使用該方法時,我得到輸出 [ab, #, cd, #, efg, #, , , , ]。 所以我不知道如何修復所有的間距,而且我還需要能夠允許我的代碼當前無法處理的多個分隔符。

我也知道這段代碼目前真的很草率,只是試圖在優化之前放下概念。

問題很簡單,你有一個偏移量來尋找新的匹配(pos),另一個顯示你找到匹配的最后一個地方的結尾(開始)。

public static String[] mySplit(String str, String regex)
{
    Vector<String> result = new Vector<String>;
    int start = 0;
    int pos = str.indexOf(regex);
    while (pos>=start) {
        if (pos>start) {
            result.add(str.substring(start,pos));
        }
        start = pos + regex.length();
        result.add(regex);
        pos = str.indexOf(regex,start); 
    }
    if (start<str.length()) {
        result.add(str.substring(start));
    }
    String[] array = result.toArray(new String[0]);
    return array;
}

這避免了額外的循環並且每個字符只復制一次。 實際上,由於子字符串的工作方式,不會復制任何字符,只會創建指向原始字符緩沖區的小字符串對象。 根本不進行字符串的串聯,這是一個重要的考慮因素。

我認為您的問題是您分配的 storeSplit[] 的長度比您需要的要長。 如果允許您使用 ArrayList,請使用它來累積結果(並使用 ArrayList.toArray() 方法獲取函數的最終返回值)。

如果您不能使用 ArrayList,那么您將需要在返回數組之前截斷它(您的計數器變量將用於確定正確的長度)。 為此,您需要分配一個正確長度的數組,然后使用 System.arraycopy 來填充它。 使用 ArrayList 更簡單,但我不知道您的作業的確切要求。

正如評論中指出的,問題在於您將數組大小設置為字符串的長度。 相反,您希望將其設置為分隔符數量的兩倍。 然后,相應地調整:

  1. a delimiter, subtract one,如果第一個字符分隔符,則減去一個,
  2. a delimiter, add one.如果最后一個字符分隔符,則添加一個。
// Calculate number of delimiters in str
int delimiters = str.length() - str.replaceAll(regex, "").length();
// Calculate array size
int arraySize = (delimiters * 2) + (str.startsWith(regex) ? -1 : 0);
arraySize = str.endsWith(regex) ? arraySize : arraySize + 1;
String[] storeSplit = new String[arraySize];

看起來您遇到的間距問題是因為您的 storeSplit 數組的長度是固定的。

假設您的輸入字符串長度為 5 個字符; 您的 storeSplit 數組將有 5 個“空格”。 該輸入字符串只能包含一個分隔符; 例如,“ab#ef”,創建 3 個子字符串——“ab”、“#”和“ef”。

為避免這種情況,請改為創建一個 List:

List<String> storeSplit = new ArrayList<String>();

然后,不要增加計數器並將文本放入其中,而是添加到列表中:

storeSplit.add(""+str.charAt(i));

而不是

storeSplit[counter] = ""+str.charAt(i);

這是我會做的:

String[] test1 = "ab#cd#efg#".split("#");//splits the string on '#'
String result="";
for(String test:test1)//loops through the array
    result+="#"+test;//adds each member to the array putting the '#' in front of each one
System.out.println(result.substring(1));//prints out the string minus the first char, which is a '#'

我希望這會有所幫助。

這是我的代碼的輸出,只需單擊它包演示;

public class demo8 {

static int count = 0;
static int first = 0;
static int j = 0;

public static void main(String[] args) {

    String s = "ABHINANDAN TEJKUMAR CHOUGULE";
    int size = 0;

    for (int k = 0; k < s.length(); k++) {
        if (s.charAt(k) == ' ') {
            size++;
        }

    }

    String[] last = new String[size + 1];

    for (int i = 0; i < s.length(); i++) {
        int temp = s.length();

        if (i == s.length() - 1) {
            last[j] = s.substring(first, i + 1);
        }

        if (s.charAt(i) == ' ') {
            last[j] = s.substring(first, i);
            j++;
            first = i + 1;

        }

    }
    for (String s1 : last) {
        System.out.println(s1);
    }
[I tested my code and output is also attached with it ...!][1]}}

我已經使用遞歸來解決它。

static void splitMethod(String str, char splitChar, ArrayList<String> list) {
        String restOfTheStr = null;
        StringBuffer strBufWord = new StringBuffer();
        int pos = str.indexOf(splitChar);
        if(pos>=0) {
            for(int i = 0; i<pos; i++) {
                strBufWord.append(str.charAt(i));
            }
            String word = strBufWord.toString();
            list.add(word);
            restOfTheStr = str.substring(pos+1);//As substring includes the 
            //splitChar, we need to do pos + 1
            splitMethod(restOfTheStr, splitChar, list);
        }
        if(pos == -1) {
            list.add(str);
            return;
        }

    }

使用:

ArrayList<String> list= new ArrayList<String>();//in this list
    //the words will be stored
    String str = "My name is Somenath";
    splitMethod(str,' ', list );

下面是方法

public static List<String> split(String str, String demarcation) {
    ArrayList<String> words = new ArrayList<>();
    int startIndex = 0, endIndex;

    endIndex = str.indexOf(demarcation, startIndex);

    while (endIndex != -1) {
        String parts = str.substring(startIndex, endIndex);

        words.add(parts);

        startIndex = endIndex + 1;
        endIndex = str.indexOf(demarcation, startIndex);

    }

    // For the last words
    String parts = str.substring(startIndex);

    words.add(parts);
    return words;
}
    public List<String> split(String str , String regex) {
    char c ;
    int count=0;
    int len = regex.length();
    String temp;
    List<String> result = new ArrayList<>();
    for(int i=0;i<str.length();i++) {
        //System.out.println(str.substring(i, i+len-1));
        temp = str.substring(i, i+len>str.length()?str.length():i+len);
        if(temp.compareTo(regex) == 0) {
            result.add(str.substring(count , i));
            count = i+len;
        }
    }
    result.add(str.substring(count, str.length()));
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM