简体   繁体   中英

How to remove lines of multiline textbox that are greater than 25 characters in length and contain no spaces, in c#?

I have a populated multi-line textbox that has a few thousand lines and occassionally has lines like this:

"e8eae9e8eae8e8ebe9e8c5c5c5eae9e8eae8e8ebe9e8eae9e8eae9e8eae8e8ebe9e8eae9e8eae9"

The values can be random, but the common denominator is that they always have over 25 characters and no spaces in the line. I would like to remove any line that meets this specification. I've tried writing the code below but it is giving me index errors.Anyone know of a good way to do this?

string[] lines = txtNotes.Lines;
List<string> tmp = new List<string>(lines);
for (int i = 0; i < lines.GetUpperBound(0); i++)
{
    if ((lines[i].Length > 25) && (!(lines[i].Contains(" "))))
    {
        tmp.RemoveAt(i);
    }
}

lines = tmp.ToArray();
txtNotes.Lines = lines;

When you call tmp.RemoveAt(i); the number elements in the tmp reduces so you can end up trying to remove element with an index that is not present in the list anymore.

You can switch your loop to run from last element to first:

for (int i = lines.Length -1 ; i > 0; i--)
{
    if  ((lines[i].Length>25) && (!(lines[i].Contains(" "))))
    {
        tmp.RemoveAt(i);
    }
}

Or just use LINQ. Something like this:

txtNotes.Lines = txtNotes.Lines
    .Where(l => l.Length <= 25 || l.Contains(" "))
    .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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