C# 如何在拆分字符串数组后获取值?
我有以下问题。在拆分之后,我希望将作者、标题和booktype放入如下变量中C# 如何在拆分字符串数组后获取值?,c#,C#,我有以下问题。在拆分之后,我希望将作者、标题和booktype放入如下变量中 string author = George Orwell string title = Animal Farm string booktype = novel 使用foreach循环很容易打印出来,但是如何获取值呢?希望有人能帮助我 static void Main(string[] args) { string[] book = new string[12]; book[0] = "George
string author = George Orwell
string title = Animal Farm
string booktype = novel
使用foreach循环很容易打印出来,但是如何获取值呢?希望有人能帮助我
static void Main(string[] args)
{
string[] book = new string[12];
book[0] = "George Orwell###Animal Farm###Novel###";
string value = book[0];
string[] item = Regex.Split(value, "###");
foreach (string newItem in item)
{
Console.WriteLine(newItem);
}
// prints out just fine
// George Orwell
// Animal Farm
// Novel
Console.ReadKey();
}
你的问题是“我如何获得这些值?”
答案是,你已经有了<代码>控制台.WriteLine(newItem)代码>
也许你的问题并不完全是你想问的;) 已拆分字符串:
string[] item = Regex.Split(value, "###");
你有一个数组。您知道第一个元素是名称,第二个是标题,第三个是类型
string author = item[0];
string title = item[1];
string booktype = item[2];
您可能应该在尝试阅读它们之前进行一些验证,但本质上就是这样。
item[0]
应该为您提供名称,item[1]
应该为您提供标题等等。您的代码表明您知道Split()
的结果是一个数组,您知道如何访问单个数组元素,你知道如何分配变量。把它们放在一起。顺序总是作者、标题和图书类型吗?如果你绝对想使用foreach
,这里有一个获取索引的主题:@MattBeldon注意Split
是字符串上的一个实例方法,而不是静态的。所以book[0].Split(新[]{“#####”},StringSplitOptions.None)代码>
//Initialise start of array
var index = 0;
//Check if array is large enough before accessing the index
if (item.Length >= index)
{
author = item[index];
index++;
}
if (item.Length >= index)
{
title = item[index];
index++;
}
//No need to increment index here as no other checks are made
if (item.Length >= index) booktype = item[index];