0

I have a problem with a String. The string is like this:

string something = "  whatever and something else  ";

Now I'm trying to get rid of the spaces at the beginning and at the end like this:

something = something.Trim();

But that didn't work, I also tried this:

something = something.TrimStart();
something = something.TrimEnd();

And this:

something = something.TrimStart(' ');
something = something.TrimEnd(' ');

And this:

int lineLength = line.Length;
string LastCharacter = line.Remove(lineLength - 1);
while (LastCharacter == " ")
{
   line = line.Remove(lineLength - 1);
   lineLength = line.Length;
   LastCharacter = line.Remove(lineLength - 1);
}

The String is Out of a RichTextBox.

Now I think it could be a problem with the Text formatting or something (I'm in Germany).

Thank you in advance, tietze111

Philipp Thi
  • 37
  • 2
  • 7
  • 2
    What language are you using? `The string is like this: ...` What do you mean by "like"? Is that the *exact* string you have? If not, where are you getting the string from, and what is the value of each character when cast to int? – Mark Byers Aug 02 '12 at 13:22
  • .Trim() should work as you expect, you're using it right. The issue is in the text contained in your string. – Alex Aug 02 '12 at 13:28
  • Thanks for answering, The Text comes Out of a richTextBox, Sorry that i forgot the Language, it's C# – Philipp Thi Aug 02 '12 at 21:09

1 Answers1

4

here's something that will rip out all white space:

 string something = " whatever    ";
 List<char> result = something.ToList();
 result.RemoveAll(c => c == ' ');
 something = new string(result.ToArray());

ok, try this for beginning and end only trims:

  static string TrimWhitespace(string theString)
    {
        theString = "  some kind of string example ";
        theString = theString.TrimEnd();
        theString = theString.TrimStart();
        // MessageBox.Show(theString, "");
        return theString;
    }
plditallo
  • 701
  • 2
  • 13
  • 31
  • Sorry, but I only want to remove the white spaces at the beginning and at the end. – Philipp Thi Aug 02 '12 at 13:37
  • I see that your code is using the same TrimEnd and TrimStart functions. I just tested what I posted, it does work. Let me (the group) know if it does not. – plditallo Aug 02 '12 at 14:57
  • Thanks for the Answer, but I Don't think this will worl, because I've already tried almost the Same. – Philipp Thi Aug 02 '12 at 21:14
  • I'm sorry, it was mine mistake, there was a space added after the Trim(), so it couldn't work properly, Thanks for the answers! – Philipp Thi Aug 03 '12 at 14:48