2014-06-26 27 views
0

我有一個字符串獲取字符串和數字

string newString = "[17, Appliance]"; 

我怎麼可以把0​​和Appliance在兩個獨立的變量,而忽略了,[]

我試過循環儘管它,但是當它到達,循環不停止,更何況它分開1 & 7,而不是讀它作爲17

+1

你可以使用'String.Replace'去除方括號,然後''String.Split''作爲分隔符... –

+0

你不必按字符來做這個字符。查找關於string.Length,string.SubString和string.Split的文檔。 – Blorgbeard

回答

0

這可能不是最高效的方法,但我會用它去爲便於理解。

string newString = "[17, Appliance]"; 
newString = newString.Replace("[", "").Replace("]",""); // Remove the square brackets 
string[] results = newString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); // Split the string 

// If your string is always going to contain one number and one string: 
int num1 = int.Parse(results[0]); 
string string1 = results[1]; 

你想要加入一些驗證,以確保您的第一個元素確實是一個數(使用int.TryParse),而且確實有拆分後的字符串返回兩個元素。

+0

是的,我理解你的答案,但是如果條目是這樣的: 「[19,烤箱烤麪包機]」,正如我在你的代碼中看到的(尚未嘗試),它將使第二個元素變成「OvenToaster」 。 –

+0

@BinurikiClieanJay不,它不會。它不會「修剪」空間,所以不會,它會返回「烤箱烤麪包機」。 [這是一個小提琴](https://dotnetfiddle.net/lMEdc7),讓您可以使用不同類型的輸入值進行遊戲。我在這裏包含了一些驗證,以確保在輸入非數字時'int.Parse'不會拋出異常,但除此之外,邏輯是相同的。 –

1

例如,你可以這樣做:

newString.Split(new[] {'[', ']', ' ', ','}, StringSplitOptions.RemoveEmptyEntries); 
+0

這對我來說是先進的格式,但如果最終用戶偶然或故意在第二個元素的字母(即「[18,Va,e]」)之間加上「,」,這可能會破壞我的數據庫,正在更新,所以我只是將其添加到我的工具中,並希望在其他情況下使用它。謝謝 –

1

這是另一種選擇,即使我不會用它,尤其是如果您可能在字符串中有多個[something, anothersomething]

不過你去那裏:

string newString = "assuming you might [17, Appliance] have it like this"; 
int first = newString.IndexOf('[')+1; // location of first after the `[` 
int last = newString.IndexOf(']'); // location of last before the ']' 
var parts = newString.Substring(first, last-first).Split(','); // an array of 2 
var int_bit = parts.First().Trim(); // you could also go with parts[0] 
var string_bit = parts.Last().Trim(); // and parts[1]