将分割字符串的第一个数字放入二维数组中

本文关键字:二维数组 数字 第一个 分割 字符串 | 更新日期: 2023-09-27 18:36:14

在 C# 控制台应用程序中,如何将拆分字符串的第一个数字放入二维数组中?

string[,] table3x3 = new string[3, 3];  
string myString = "11A23A4A5A87A5"; 
string[] splitA = myString.Split(new char[] { 'A' });

假设我有 3x3 的二维数组和一个带有数字和元音的字符串。我将它们分开,以便将它们放入 2Darray 中。我应该包含什么样的循环,以便输出

Console.WriteLine(table3x3[0, 0]); //output: blank
Console.WriteLine(table3x3[0, 1]); //output: blank
Console.WriteLine(table3x3[0, 2]); //output: 2
Console.WriteLine(table3x3[1, 0]); //output: blank
Console.WriteLine(table3x3[1, 1]); //output: 4
Console.WriteLine(table3x3[1, 2]); //output: 5
Console.WriteLine(table3x3[2, 0]); //output: 8
Console.WriteLine(table3x3[2, 1]); //output: blank
Console.WriteLine(table3x3[2, 2]); //output: 5

从视觉上看,输出如下所示:

[ ][ ][2]
[ ][4][5]
[8][ ][5]

字符串内有 9 个数字和 5 个元音。它根据序列将拆分字符串的第一个数字返回到特定的 2Darray 中。

将分割字符串的第一个数字放入二维数组中

这应该可以做到:

string[,] table3x3 = new string[3, 3];  
string myString = "11A23A4A5A87A5";
int stringIndex = -1;
bool immediatelyFollowsA = false;
for (int row = 0; row < 3; row++)
    for (int col = 0; col < 3; col++)
    {
        while (myString[++stringIndex] == 'A')
        {
            immediatelyFollowsA = true;
        }
        if (immediatelyFollowsA)
        {
            table3x3[row,col] = myString[stringIndex].ToString();
            immediatelyFollowsA = false;
        }
    }

演示:http://ideone.com/X0LdF


或者,添加到您的原始起点:

string[,] table3x3 = new string[3, 3];  
string myString = "11A23A4A5A87A5";
string[] splitA = myString.Split(new char[] { 'A' });
int index = 0;
bool first = true;
foreach (string part in splitA)
{
    int row = index / 3;
    int col = index % 3;
    if (!first)
    {
        table3x3[row, col] = part[0].ToString();
    }
    index += part.Length;
    first = false;
}

演示:http://ideone.com/7sKuR