Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在拆分字符串数组后获取值?_C# - Fatal编程技术网

C# 如何在拆分字符串数组后获取值?

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

我有以下问题。在拆分之后,我希望将作者、标题和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 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];