c#
  • .net
  • arrays
  • 2016-05-27 198 views 0 likes 
    0

    是否有將字符串拆分爲數組的方法?該字符串有兩個或更多的分隔符。使用分隔符c將字符串拆分爲一個點#

    string testString = @"test=key=value"; 
    

    使用'='作爲分隔符。我如何將字符串拆分爲兩個索引的數組?

    string testString = @"test=key=value"; 
             //^Split Here 
    

    陣列將導致:{「測試」,「鍵=值」}

    +0

    http://stackoverflow.com/questions/1000831/how-can-i-split-the-string-only-once-using-c-sharp – pw94

    回答

    1

    如果使用string.IndexOf這將返回等號的第一次出現的索引標誌。然後,您可以分割使用SubString字符串:

    int index = testString.IndexOf('='); 
    string first = testString.SubString(0, index).Trim(); 
    string second = testString.SubString(index+1).Trim(); 
    

    Trim的通話將刪除任何空白,可能是周圍的等號。

    另外,您可以使用此string.Split重載,將您希望返回(在這種情況下2)的字符串的最大數量:

    var result = string.Split(new[] { '=' }, 2); 
    

    您仍然需要Trim結果來刪除空白。

    Thanks Richard

    +0

    或者使用'VAR keyValuePair = string.Split(new [] {'='},2);'這隻會在第一次出現equals時分裂。 –

    相關問題