【问题标题】:How to store every 2 characters in c#如何在c#中存储每2个字符
【发布时间】:2013-03-15 16:53:27
【问题描述】:

有没有办法将每 2 个字符存储在一个字符串中?

例如

1+2-3-2-3+

所以它可以是“1+”、“2-”、“3-”、“2-”、“3+”作为单独的字符串或数组。

【问题讨论】:

  • 什么编程语言?
  • 请显示您尝试过但有问题的代码。
  • 嗯,遍历字符串并将每个子字符串副本移动到数组中?如果这是您第一次接触 C#,这里有很多在线资源和书籍。我会从那里开始。

标签: c# store


【解决方案1】:

最简单的方法是循环遍历字符串,并从当前位置获取两个字符的子字符串:

var res = new List<string>();
for (int i = 0 ; i < str.Length ; i += 2)
    res.Add(str.Substring(i, 2));

高级解决方案可以使用 LINQ 做同样的事情,并避免显式循环:

var res = Enumerable
    .Range(0, str.Length/2)
    .Select(i => str.Substring(2*i, 2))
    .ToList();

第二种解决方案更紧凑,但更难理解,至少对于不熟悉 LINQ 的人来说是这样。

【讨论】:

    【解决方案2】:

    这对于正则表达式来说是一个很好的问题。你可以试试:

    \d[+-]
    

    只需找到如何编译该正则表达式 (HINT) 并调用返回所有匹配项的方法。

    【讨论】:

    • +1。危险(正则表达式可能很快变得不可读),但至少是一种不同的方法。
    【解决方案3】:

    使用 for 循环,并使用 string.Substring() 方法提取字符,确保不会超出字符串的长度。

    例如

    string x = "1+2-3-2-3+";
    const int LENGTH_OF_SPLIT = 2;
    for(int i = 0; i < x.Length(); i += LENGTH_OF_SPLIT)
    {
        string temp = null; // temporary storage, that will contain the characters
    
        // if index (i) + the length of the split is less than the
        // length of the string, then we will go out of bounds (i.e.
        // there is more characters to extract)
        if((LENGTH_OF_SPLIT + i) < x.Length())
        {
            temp = x.Substring(i, LENGTH_OF_SPLIT);
        }
        // otherwise, we'll break out of the loop
        // or just extract the rest of the string, or do something else
        else
        {
             // you can possibly just make temp equal to the rest of the characters
             // i.e.
             // temp = x.Substring(i);
             break; // break out of the loop, since we're over the length of the string
        }
    
        // use temp
        // e.g.
        // Print it out, or put it in a list
        // Console.WriteLine(temp);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-28
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2011-03-16
      • 2017-08-24
      相关资源
      最近更新 更多