得到字符串和数字

时间:2014-06-26 03:25:30

标签: c# string

我有一个字符串

string newString = "[17, Appliance]";

如何将17Appliance放在两个单独的变量中,同时忽略,[以及]

我尝试循环虽然它但循环在到达,时没有停止,更不用说它分开1& 7而不是将其读作17。

3 个答案:

答案 0 :(得分:1)

例如,你可以使用它:

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

答案 1 :(得分: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]

答案 2 :(得分: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),并且在拆分字符串后确实返回了两个元素。

相关问题