简体   繁体   English

在C#Win中从字符串中删除字符的最佳方法。 形成

[英]Best way to remove characters from string in c# win. form

i have a string of length 98975333 and i need to remove first 5 letters in it. 我有一个长度为98975333的字符串,我需要删除其中的前5个字母 Can anyone suggest the best way to do this keeping performance in mind ? 任何人都可以提出最佳方法来牢记性能吗?

I tried 我试过了

 str.Substring(5,str.Length);
 str.Remove(0,5);

which gives me result in 0.29 sec but i want something even faster than the above. 这给了我0.29秒的结果,但是我想要比以上更快的速度。

Problem Using StringBuilder 使用StringBuilder时出现问题

-> i need to substring a part of the string and to do this i need to write ->我需要对字符串的一部分进行子字符串化,为此我需要写

 StringBuilder2.ToString().Substring(anyvaluehere)"

here the conversion of StringBuilder to string by ".ToString()" takes time and in this case i cant use StringBuilder 在这里“ .ToString()”将StringBuilder转换为字符串需要时间,在这种情况下,我不能使用StringBuilder

Sorry, c# strings are not arrays; 抱歉,c#字符串不是数组; they are immutable so extracting a (possibly very long) substring involves a copy. 它们是不可变的,因此提取(可能很长)子字符串会涉及一个副本。

However, most [string utilities] accept start and end indices, for instance IndexOf and CompareInfo.Compare all take a startIndex overload. 但是,大多数[字符串工具]都接受开始和结束索引,例如IndexOfCompareInfo.Compare都具有startIndex重载。

Perhaps if you tell us what you want to do afterward we could suggest alternatives? 也许如果您告诉我们您以后想要做什么,我们可以建议替代方法?

Update 更新

Here are some ways you can write performant string parsing with the immutable strings in c#. 您可以通过以下几种方法使用c#中的不可变字符串编写高效能的字符串解析。 Say for instance that you need to deserialize XML data inside the string, and need to skip the first N characters. 假设您需要在字符串中反序列化XML数据,并且需要跳过前N个字符。 You could do something like this: 您可以执行以下操作:

    public static object XmlDeserializeFromString<T>(this string objectData, int skip)
    {
        var serializer = new XmlSerializer(typeof(T));

        using (var reader = new StringReader(objectData))
        {
            for (; skip > 0 && reader.Read() != -1; skip--)
                ;
            return (T)serializer.Deserialize(reader);
        }
    }

As you can see from the source . 源头上可以看到。 StringReader.Read() does not make a copy of the unread portion of the string, it keeps an internal index to the remaining unread portion. StringReader.Read()不会复制字符串的未读部分,而是保留到其余未读部分的内部索引。

Or say you want to skip the first N characters of a string, then parse the string by splitting it at every "," character. 或者说您要跳过字符串的前N个字符,然后通过在每个“,”字符处分割字符串来解析该字符串。 You could write something like this: 您可以这样写:

    public static IEnumerable<Pair<int>> WalkSplits(this string str, int startIndex, int count, params char[] separator)
    {
        if (string.IsNullOrEmpty(str))
            yield break;
        var length = str.Length;
        int endIndex;
        if (count < 0)
            endIndex = length;
        else
        {
            endIndex = startIndex + count;
            if (endIndex > length)
                endIndex = length;
        }

        while (true)
        {
            int nextIndex = str.IndexOfAny(separator, startIndex, endIndex - startIndex);
            if (nextIndex == startIndex)
            {
                startIndex = nextIndex + 1;
            }
            else if (nextIndex == -1)
            {
                if (startIndex < endIndex)
                    yield return new Pair<int>(startIndex, endIndex - 1);
                yield break;
            }
            else
            {
                yield return new Pair<int>(startIndex, nextIndex - 1);
                startIndex = nextIndex + 1;
            }
        }
    }

And then use the start and end indices of the Pair to further parse the string, or extract small substrings to feed to further parsing methods. 然后,使用Pair的开始和结束索引进一步解析字符串,或提取小的子字符串以提供给进一步的解析方法。

( Pair<T> is a small struct I created similar to KeyValuePair<TKey, TValue> but with identically typed first and second values. I can provide if needed.) Pair<T>是我创建的一个小结构,类似于KeyValuePair<TKey, TValue>但是具有相同的第一和第二个值。如果需要,我可以提供。)

If you are working with long strings, always use StringBuilder. 如果使用长字符串,请始终使用StringBuilder。 This class provides you fast adding and removing characters, faster than String.Concat or it's syntactic sugar "a" + "b". 此类比String.Concat或它的语法糖“ a” +“ b”更快,可为您提供快速添加和删除字符的功能。 Moreover StringBuilder.ToString() method has special implementation for best performance as possible. 此外,StringBuilder.ToString()方法具有特殊的实现,以实现最佳性能。

Using a StringBuilder to produce and manipulate the string will help you save on resources: 使用StringBuilder生成和处理字符串将帮助您节省资源:

   StringBuilder sb = new StringBuilder();

    sb.Append("text"); //to add text in front

    sb.Insert(50,"text"); // to insert text

    sb.Remove(50,4); // to remove text

    sb.ToString(); // to produce the string

If you have a fixed length of string that you wish to store elsewhere, you can make a char array and use StringBuilder's CopyTo() method: 如果您希望将固定长度的字符串存储在其他位置,则可以创建一个char数组,并使用StringBuilder的CopyTo()方法:

eg 例如

    char[] firstfive = new char[5];
    sb.CopyTo(0,firstfive,0,5);

Edit: 编辑:

Actually, the OP figured this out himself, but I'm including it on the post for reference: 实际上,OP自己解决了这个问题,但我将其包含在帖子中以供参考:

To get a portion of the StringBuilder as string: 要将StringBuilder的一部分作为字符串获取:

sb.ToString(intStart,intLength)

Use String.Remove() ie 使用String.Remove()

String newStr = "";
newStr = str.Remove(0,5); //This will delete 5 characters starting from 0 index 

Or 要么

newStr = str.Remove(5); //Assumes the starting position as 0 and will ddelete 5 chars from that

Read more Here 在这里阅读更多

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

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