简体   繁体   English

你如何在 C# 中用 2 个字符计数拆分字符串?

[英]How do you do a string split with 2 chars counts in C#?

I know how to do a string split if there's a letter, number, that I want to replace.如果有我想替换的字母、数字,我知道如何进行字符串拆分。

But how could I do a string.Split() by 2 char counts without replacing any existing letters, number, etc...?但是我怎么能在不替换任何现有字母、数字等的情况下按 2 个char计数执行string.Split()

Example:例子:

string MAC = "00122345"

I want that string to output: 00:12:23:45我希望该字符串输出:00:12:23:45

You could create a LINQ extension method to give you an IEnumerable<string> of parts:您可以创建一个 LINQ 扩展方法来为您提供IEnumerable<string>部分:

public static class Extensions
{
    public static IEnumerable<string> SplitNthParts(this string source, int partSize)
    {
        if (string.IsNullOrEmpty(source))
        {
            throw new ArgumentException("String cannot be null or empty.", nameof(source));
        }

        if (partSize < 1)
        {
            throw new ArgumentException("Part size has to be greater than zero.", nameof(partSize));
        }

        return Enumerable
            .Range(0, (source.Length + partSize - 1) / partSize)
            .Select(pos => source
                .Substring(pos * partSize, 
                    Math.Min(partSize, source.Length - pos * partSize)));
    }
}

Usage:用法:

var strings = new string[] { 
    "00122345", 
    "001223453" 
};

foreach (var str in strings)
{
    Console.WriteLine(string.Join(":", str.SplitNthParts(2)));
}
// 00:12:23:45
// 00:12:23:45:3

Explanation:解释:

  • Use Enumerable.Range to get number of positions to slice string.使用Enumerable.Range获取切片字符串的位置数。 In this case its the length of the string + chunk size - 1 , since we need to get a big enough range to also fit leftover chunk sizes.在这种情况下,它是length of the string + chunk size - 1length of the string + chunk size - 1 ,因为我们需要获得足够大的范围以适应剩余的块大小。
  • Enumerable.Select each position of slicing and get the startIndex using String.Substring using the position multiplied by 2 to move down the string every 2 characters. Enumerable.Select切片的每个位置并使用String.Substring获取startIndex使用位置乘以 2 以每 2 个字符向下移动字符串。 You will have to use Math.Min to calculate the smallest size leftover size if the string doesn't have enough characters to fit another chunk.如果字符串没有足够的字符来容纳另一个块,您将不得不使用Math.Min来计算最小的剩余大小。 You can calculate this by the length of the string - current position * chunk size .您可以通过length of the string - current position * chunk sizelength of the string - current position * chunk size
  • String.Join the final result with ":" . String.Join最终结果与":"

You could also replace the LINQ query with yield here to increase performance for larger strings since all the substrings won't be stored in memory at once:您还可以在此处用yield替换 LINQ 查询以提高较大字符串的性能,因为所有子字符串不会一次存储在内存中:

for (var pos = 0; pos < source.Length; pos += partSize)
{
    yield return source.Substring(pos, Math.Min(partSize, source.Length - pos));
}

You can use something like this:你可以使用这样的东西:

string newStr= System.Text.RegularExpressions.Regex.Replace(MAC, ".{2}", "$0:");

To trim the last colon, you can use something like this.要修剪最后一个冒号,您可以使用这样的方法。

    newStr.TrimEnd(':');

Microsoft Document 微软文档

Try this way.试试这个方法。

    string MAC = "00122345";
    MAC = System.Text.RegularExpressions.Regex.Replace(MAC,".{2}", "$0:");
    MAC = MAC.Substring(0,MAC.Length-1);
    Console.WriteLine(MAC);

An easy to understand and simple solution.一个易于理解和简单的解决方案。

This is a simple fast modified answer in which you can easily change the split char .这是一个简单的快速修改答案,您可以在其中轻松更改 split char

  • This answer also checks if the number is even or odd , to make the suitable string.Split() .这个答案还检查数字是even还是odd ,以制作合适的string.Split()

input : 00122345输入:00122345

output : 00:12:23:45输出:00:12:23:45


input : 0012234输入:0012234

output : 00:12:23:4输出:00:12:23:4



//The List that keeps the pairs
List<string> MACList = new List<string>();

//Split the even number into pairs
for (int i = 1; i <= MAC.Length; i++)
{               
    if (i % 2 == 0)
    {
        MACList.Add(MAC.Substring(i - 2, 2));
    }
}

//Make the preferable output
string output = "";
for (int j = 0; j < MACList.Count; j++)
{
    output = output + MACList[j] + ":";
}

//Checks if the input string is even number or odd number
if (MAC.Length % 2 == 0)
{
    output = output.Trim(output.Last());
}
else
{
    output += MAC.Last();
}

//input : 00122345
//output : 00:12:23:45

//input : 0012234
//output : 00:12:23:4

A quite fast solution, 8-10x faster than the current accepted answer (regex solution) and 3-4x faster than the LINQ solution一个相当快的解决方案,比当前接受的答案(正则表达式解决方案)快 8-10 倍,比 LINQ 解决方案快 3-4 倍

public static string Format(this string s, string separator, int length)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.Length; i += length)
    {
        sb.Append(s.Substring(i, Math.Min(s.Length - i, length)));
        if (i < s.Length - length)
        {
            sb.Append(separator);
        }
    }

    return sb.ToString();
}

Usage:用法:

string result = "12345678".Format(":", 2);

这是使用LINQ Enumerable.Aggregate的一 (1) 行替代方法。

string result = MAC.Aggregate("", (acc, c) => acc.Length % 3 == 0 ? acc += c : acc += c + ":").TrimEnd(':');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM