将字符串分割/数每隔N个字符/数字? [英] Splitting a string / number every Nth Character / Number?

查看:277
本文介绍了将字符串分割/数每隔N个字符/数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些分成甚至部分,例如:
32427237需要成为324 272 37
103092501要成为103 092 501

I need to split a number into even parts for example:
32427237 needs to become 324 272 37
103092501 needs to become 103 092 501

我敢肯定,我可以换旁边的数字,但我敢肯定有,因为我不想错过的人物在这些数字更有效的方式 - 数字本身可能是这样,如果任意长度数量分别为1234567890我希望它分为以下部分123 456 789 0

I'm sure I could just for-next the numbers, but I'm sure there is a more efficient way as I don't want to miss the characters in these numbers - the numbers themselves can be any length so if the number were 1234567890 I'd want it split into these parts 123 456 789 0

我已经看到了在其他语言如Python等例子,但我不明白他们不够好,将它们转换为C# - 循环尽管字符,然后在第三个获得previous,然后该索引得到字符串的部分可以做的工作,但我愿意就如何实现这一目标提出更好的建议。

I've seen examples in other languages like Python etc but I don't understand them well enough to convert them to C# - looping though the characters and then at the third getting the previous and then that index to get the section of the string may do the job, but I'm open to suggestions on how to accomplish this better.

推荐答案

如果您需要做的是,在许多地方在code,你可以创建一个奇特的扩展方法:

If you have to do that in many places in your code you can create a fancy extension method:

static class StringExtensions {

  public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
    if (s == null)
      throw new ArgumentNullException("s");
    if (partLength <= 0)
      throw new ArgumentException("Part length has to be positive.", "partLength");

    for (var i = 0; i < s.Length; i += partLength)
      yield return s.Substring(i, Math.Min(partLength, s.Length - i));
  }

}

然后就可以使用这样的:

You can then use it like this:

var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));

输出为 324 272 37 的期望。

这篇关于将字符串分割/数每隔N个字符/数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆