2

在 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 中。

4

1 回答 1

2

这应该这样做:

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

于 2012-06-01T23:51:58.327 回答