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

标签 c# multidimensional-array split

在 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 个元音。它根据序列将分割字符串的第一个数字返回到特定的二维数组中。

最佳答案

这应该可以做到:

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

关于c# - 将分割字符串的第一个数字放入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10858535/

相关文章:

C - 将动态分配的 3D 矩阵传递给函数

javascript - 拆分多个字符的问题

python - 在列表中没有分隔符的情况下在多个分隔符处拆分

c# - WPF - VirtualPanel/ZoomableCanvas - 在 ObservableCollection 中查找对象交集的最快方法?

c# - Visual Studio 2010 专业版 : class diagram tool

c# - MiniProfiler 没有出现在 ASP.NET Core 中

javascript - LoDash - 如何通过公用 key 将一个集合值推送到另一个集合中

javascript - jScript - 如何 "mirror"矩阵(多维数组)

Java拆分方法

c# - 如何配置两个JSON序列化器并根据路由选择正确的一个