2011-03-21 32 views
1

我有一個多字符串是這樣的:如何比較字符串與另一個字符串的更小和更小的部分?

String Y = "part1 part2 part3 part4"; // This is only an example value 

我想寫的是完整的序列Y與另一〜應變比較功能,X.(通常情況下,我將其與列表進行比較。)如果字符串如果不相等,則X應與part1 part2進行比較,最後用part1

我可以使用split(" ")來打斷字符串。我不知道字符串中的塊的數量。我如何編寫這種比較方法?

+0

一個例子闡明瞭很多。 – aioobe 2011-03-21 20:21:32

回答

3

您可以使用這樣的算法:

boolean foundMatch = false; 
while(!foundMatch) { 
    foundMatch = Y.equals(X); 
    if(foundMatch) { 
     break; 
    } 
    else { 
     Y = Y.useSplitToRemoveLastPart(); 
     if(Y.equals("")) { 
      break; 
     } 
    } 
} 

這只是僞代碼,當然。看起來好像你有一個大概的想法如何去做每個單獨的部分。如果您需要更多指導,請告訴我。

編輯:
假設你的字符串將永遠是空間分隔的像他們在你的榜樣,你可以做這樣的事情:

String userSplitToRemoveLastPart(String Y) { 
    // Find the last space 
    int lastSpace = Y.lastIndexOf(" "); 

    // Return only the part of the string that comes before the last space 
    return Y.substring(0, lastSpace); 
} 

我沒有測試過這一點,它可能是執行拆分的最有效方式,但我認爲該算法很清晰。

+0

你能更清楚地瞭解內部使用情況SplitToRemoveLastPart() – 2011-03-23 16:36:52

+1

@Praneel,我更新了。完全不使用'split()',因爲我想到了一個更簡短的方法。 – Pops 2011-03-23 18:02:09

+0

非常感謝@ Torgamus閣下 – 2011-03-24 14:53:56

1

像這樣的東西應該讓你開始:

class SpecialComparator implements Comparator<String> { 

    public int compare(String o1, String o2) { 

     // Get parts to compare 
     String[] words1 = o1.split(" "); 
     String[] words2 = o2.split(" "); 

     // Reverse arrays to start with the last word first. 
     Collections.reverse(Arrays.asList(words1)); 
     Collections.reverse(Arrays.asList(words2)); 

     int n = Math.min(words1.length, words2.length); 

     for (int i = 0; i < n; i++) { 
      int result = words1[n].compareTo(words2[i]); 

      if (result != 0)  // not equal, differing words found. 
       return result; 
     } 

     // Deal with the situation in which the strings are of different length. 
     // ... 

     // They're equal. 
     return 0; 
    } 
} 
1

我有點糊塗了你的預期結果。我們的目標似乎是簡單地數部分匹配,此完成:

public boolean foo(final String str1, final String str2) { 
    return Pattern.matches(" " + str1 + " (.*)", " " + str2 + " "); 
} 

一些測試:

String target = "part1 part2 part3 part4"; 
foo("part1 part2 part3 part4", target); // true 
foo("part1 part2 part3", target); // true 
foo("part1 part2", target); // true 
foo("part1", target); // true 
foo("part1 part3", target)); // false 
+0

@Lord Torgamus - 不,它不會,因爲'匹配'「試圖匹配整個輸入序列與模式。」 – 2011-03-22 17:27:49

+0

你是對的。看起來,我現在對正規表達式並沒有那麼敏銳。刪除我的評論和upvoting你。 – Pops 2011-03-22 17:40:14

+0

@主 - 這種行爲總是讓我思考三次,因爲我不認爲我的正則表達式總是暗含'^'和'$' – 2011-03-22 17:41:46

相關問題