【问题标题】:How do i split a text 2 by 2?如何将文本 2 拆分为 2?
【发布时间】:2021-08-17 11:57:07
【问题描述】:

变量是:你好 我想要的结果:

split[0] = he;
split[1] = ll;
split[2] = o + ( space );

我试过这段代码:

string[] split = new string[text.Length / 2 + (text.Length % 2 == 0 ? 0 : 1)];
for (int i = 0; i < split.Length; i++)
{
  split[i] = text.Substring(i, i + 2 > text.Length ? 1 : 2);
}

输出是“He el lo”(它是第二个字符的两倍)。

【问题讨论】:

  • 您可能希望将您的编程语言作为标签添加到您的问题中。
  • 提示:在一张纸上,在脑海中运行代码。请注意:如果您指定了您正在使用的语言,例如使用相应的标签,这将有所帮助。并且:如果您只添加一个 " " 空格,以防输入的长度不均匀,您可以让您的生活更轻松。
  • 并提示:检查你的代码,问问自己i 的值是什么。它应该达到什么价值。
  • 我不明白为什么“Hello”会这样拆分。多余的空间从何而来?它在原始字符串中吗?还是仅在字符数为奇数时用作填充?
  • 我是bored

标签: c# arrays string split


【解决方案1】:

试试这个:

string input = "Hello"
string[] split = new string[input.Length / 2 + (input.Length % 2 == 0 ? 0 : 1)];
for (int i = 0; i < input.Length; i+=2)
{
    split[i/2] = input.Substring(i, i + 2 > input.Length ? 1 : 2);
}

这会以 2 为增量逐步遍历输入字符串,每次输入 2 个字符。

【讨论】:

    【解决方案2】:

    我认为这段代码会有所帮助:

     string text = "1234567";
            int loop = text.Length / 2 + (text.Length % 2 == 0 ? 0 : 1);
            List<string> split = new List<string>();
            int readTotal = 0;
            int textLen = text.Length;
            for (int i = 0; i < loop; i++)
            {
                if (textLen- readTotal >= 2)
                    split.Add(text.Substring(i * 2, 2));
                else
                    split.Add(text.Substring(i * 2, 1));
                readTotal += 2;
    
            }
    

    【讨论】:

    • 首先,您必须在 Substring 第二种方法中传递参数作为您想要阅读的文本量,因此如果我到达具有奇数个字母的文本的末尾,我会传递 2 或 1。其次,我添加了一个 readTotal 变量来检查我读取了多少以及在字符串末尾要达到多少。
    • 欢迎您。请将此答案设置为有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多