我有一個字符串形式爲比較兩個不同順序的字符串
PosAttributes:FN,CT,ST;
現在,當我計算的一些功能我得到一個字符串作爲
PosAttributes1:FN,ST,CT;
現在雖然兩個字符串都表示相同的事情,並且如果使用下面的相同函數,它將返回false。我知道兩種叮咬都不一樣,但語義是相同的。我該怎麼辦?
PosAttributes.equals(PosAttributes);
我有一個字符串形式爲比較兩個不同順序的字符串
PosAttributes:FN,CT,ST;
現在,當我計算的一些功能我得到一個字符串作爲
PosAttributes1:FN,ST,CT;
現在雖然兩個字符串都表示相同的事情,並且如果使用下面的相同函數,它將返回false。我知道兩種叮咬都不一樣,但語義是相同的。我該怎麼辦?
PosAttributes.equals(PosAttributes);
由於字符串由逗號delimitered您可以使用String.split給
String arr[] = PosAttributes.split (",");
String arr2[] = PosAttributes1.split (",");
那麼你只要通過第一陣列,確保所有的元素都是第二陣列中需要循環。還要檢查尺寸是否相同。
我可以確保只有一個if語句中的語義相同嗎? –
@UditPanchal我懷疑它,不是如果你想要它可讀 – MadProgrammer
創建一個方法,爲你做到這一點。 – deyur
您需要分解每個字符串的各個部分,並將它們存儲在某種Set中 - 這是一種結構,其中無任何訂單,或訂單不影響方法的結果。我會寫一個像這樣的方法。
private static Set<String> attributeSet(String input) {
String[] attributes = input.split(",");
return new HashSet<String>(Arrays.asList(attributes));
}
如果分隔符是逗號,這會將字符串分解爲其片段。然後它使用標準技巧將結果數組轉換爲HashSet
,這是一種常用的類型Set
。
然後,當我要比較兩個字符串,我可以寫類似
if (attributeSet(string1).equals(attributeSet(string2))) {
// ...
}
這種方法僅適用於字符串不能包含重複項的情況。例如「FN,CT,ST,FN」不是有效的字符串。否則,該字符串將被視爲等於「FN,CT,ST」。直到OP是否這是一個問題。 – deyur
是的,的確如此。聽起來像是我應該在問題下提出的評論。謝謝@deyur。 –
所以假設例如文本全文,你需要刪除;
字符,因爲這會改變內容在String
的,對,
性格分裂String
,得到的數組進行排序,並比較他們,像...
String[] v1 = "FN,CT,ST;".replace(";", "").split(",");
String[] v2 = "FN,ST,CT;".replace(";", "").split(",");
Arrays.sort(v1);
Arrays.sort(v2);
System.out.println(Arrays.equals(v1, v2));
,輸出true
我可能會嘗試做的是寫一個返回的String
的有序數組,複製所有的常用功能的方法...
public static String[] sorted(String value) {
String[] v1 = value.replace(";", "").split(",");
Arrays.sort(v1);
return v1;
}
然後你可以簡單地調用它,這將使你做一個像比較...
System.out.println(Arrays.equals(sorted("FN,CT,ST;"), sorted("FN,ST,CT;")));
下一步可能是寫返回true
的方法,即要求sorted
和Arrays.equals
,使其更容易...
System.out.println(isEqual("FN,CT,ST;", "FN,ST,CT;"));
不過,我會離開,你;)
您可以覆蓋等方法或排序都串,然後對它們進行比較。
我現在有相同的工作要求,並希望避免使用列表進行評估。
我所做的是檢查兩個要比較的字符串長度是否相等 - 這意味着它們可能是相同的,只是順序不同而已。
現在在主字符串中逐個刪除逗號分隔的字符串,該字符串位於比較字符串中。如果主字符串的輸出是空的,這意味着兩者是精確的數學。請參閱下面的僞代碼(我沒有粘貼實際的代碼,因爲它有一些公司特定的信息):
private static boolean isStringCombinationEqual(final String main, final String compare)
{
boolean result = false;
String modifiedMain = main;
// if not the same length, then cannot possibly be same combination in different order
if (main.length() == compare.length())
{
final String[] compareArr = // split compare using delimiter
for (int i = 0; i < compareArr.length; i++)
{
if (i > 0)
{
modifiedMain = // replace delimiter with empty string
}
modifiedMain = // replace compareArr[0] with empty string
}
if (//modifiedMain is empty)
{
result = true;
}
}
return result;
}
是否有可能您的字符串將包含重複的屬性?如果是這樣,那麼具有不同重複值的字符串是否應該被視爲不同?例如,「FN,ST,CT,CT」等於「CT,FN,ST,ST」嗎? –