提问人:Johnny Long 提问时间:12/6/2020 更新时间:12/6/2020 访问量:141
来自引号中单词的 C# 子字符串
c# substring from a word in quotes
问:
我正在尝试使用子字符串从字符串中获取值,如下所示:
surname='Smith',name="John"
我基本上想使用文本“name”和引号来获得值“John”。
有没有办法做到这一点?
答:
0赞
MundoPeter
12/6/2020
#1
有很多方法可以做到这一点。 这是其中之一:
char[] quotes = { '\'', '\"' };
string input = "surname='Smith',name=\"John\"";
string[] sections = input.Split(',');
for (int i = 0; i < sections.Length; i++)
{
string[] pair = sections[i].Split('=');
if (pair[0] == "surname")
Debug.WriteLine("surname=" + pair[1].Trim(quotes));
if (pair[0] == "name")
Debug.WriteLine("name=" + pair[1].Trim(quotes));
}
0赞
coder_b
12/6/2020
#2
可以使用 LINQ 查询来获取名称
var query = @"surname='Smith',name = \""John\""";
var name = query
.Split(',')
.Select(s => new KeyValuePair<string, string>(
s.Split('=').GetValue(0).ToString().Trim(),
s.Split('=').GetValue(1).ToString().Trim()
))
.FirstOrDefault(kvp => kvp.Key == "name").Value;
Console.WriteLine(name);
评论
.拆分()