Search code examples
c#stringtrim

Why is String.Trim not trimming a semicolon?


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.


Solution

  • 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.