简体   繁体   English

使用Char C#分割字串

[英]Splitting a String with Char C#

How can I efficiently split a string with a character? 如何有效地用字符分割字符串?

An example would be: 一个例子是:

inputString = "ABCDEFGHIJ", sectionLength = 4, splitChar = '-', and output = "ABCD-EFGH-IJ" inputString =“ ABCDEFGHIJ”,sectionLength = 4,splitChar ='-',输出=“ ABCD-EFGH-IJ”

Here is my first attempt: I wanted to split an input string with certain chars after every nth interval. 这是我的第一次尝试:我想在每第n个间隔后用某些字符分割输入字符串。 I am wondering if there is a more efficient way to do this, or if I am missing something that could fail. 我想知道是否有更有效的方法来执行此操作,或者是否缺少可能失败的内容。 I believe the If statement at the beginning should catch any invalid input, save null input. 我认为开头的If语句应捕获任何无效输入,请保存空输入。

public String SplitString(string inputString, int sectionLength, 
    char splitChar)
{
    if (inputString.Length <= sectionLength || sectionLength < 1)
        return inputString;

    string returnString = "";
    int subStart;
    int end = inputString.Length;

    for (subStart = 0 ; (subStart + sectionLength) < end; 
        subStart += sectionLength)
    {
        returnString = returnString +
            inputString.Substring(subStart,
            sectionLength) + splitChar;
    }

    return returnString + inputString.Substring(subStart, 
        end - subStart);
}

Strings in .NET are immutable . .NET中的字符串是不可变的 That means operations that combine strings end up creating a brand-new string. 这意味着组合字符串的操作最终会创建一个全新的字符串。

This section of code 本节代码

for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
    {
        returnString = returnString + inputString.Substring(subStart, sectionLength) + splitChar;
    }

keeps creating new strings. 不断创建新的字符串。

Instead, explore the use of StringBuilder. 而是,探索StringBuilder的用法。

int estimatedFinalStringLength = 100; // <-- Your estimate here
StringBuilder returnString = new StringBuilder(estimatedFinalStringLength);
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
    returnString.Append(inputString.Substring(subStart, sectionLength) + splitChar);
}

return returnString.ToString() + inputString.Substring(subStart, end - subStart);

Doing your best to estimate the total length of the final string will reduce the number of buffer reallocations that StringBuilder does internally. 尽最大可能估算最终字符串的总长度将减少StringBuilder在内部执行的缓冲区重新分配的次数。

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

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