Why is String.Trim not trimming a semicolon?

904 Views Asked by At

I'm trying to trim a string with String.Trim:

split[2].Trim(';')

But I'm getting the result of:

System;

Instead of:

System

I also tried using:

split[2].TrimEnd(';')

But it still returns the same result.

Also if I do:

split[2].Trim('S', ';')

I get:

ystem;

I'm really confused why this is happening. Could it be because the semicolon is not the last character in the string?

Here is the full code:

string line = @"
using System;
using System.Windows.Forms;
class HelloWorld
{
    static void Main()
    {
#if DebugConfig
        Console.WriteLine("WE ARE IN THE DEBUG CONFIGURATION");  
#endif

        Console.WriteLine("Hello, world!");
        DialogResult result;
        result = MessageBox.Show("Itsyeboi", "Yup", MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes)
        {
            Console.WriteLine("Yes");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("No");
            Console.ReadLine();
        }

    }
}"
string[] split = line.Split(' ', '\n');
while (true)
{
    if (split[counter4] == "using")
    {
        richTextBox1.Text = split[1].Trim(';');
        break;
    }
    else
    {
          richTextBox1.Text = line;
        break;
    }
}

It's true that my while loop is pointless, but it is "WIP" and not the final version.

2

There are 2 best solutions below

2
On BEST ANSWER

Replace the following line:

string[] split = line.Split(' ', '\n');

With this:

string[] split = line.Replace("\r\n", "\n").Split(' ', '\n');

This will replace any carriage returns with just newline characters, removing the possibility that a trailing \r may be causing your problem.

0
On

If this answer is wrong, I'll delete it. As the information is sparse, this is only a wild guess.

Inserting a

split[2].Trim()

right befor the

split[2].Trim(';')

will most likely do the trick.

If not, but you know the last char is a ; and you only want to get rid of this you may also just slice your array. This would probably be more efficient, as you would not need to compare any chars, while this is most likely done at least twice if you use TrimEnd or thrice if you yous Trim