Search code examples
c#stringspecial-characterstrim

Strange behavior string.Trim method


I want to remove all spaces(only ' ' and '\t', '\r\n' should stay) from string. But i have problem.

Example: if i have

string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
string res = test.Trim(); // res still "902322\t\r\n900657\t\r\n10421\t\r\n" 
res = test.Trim('\t'); // res still "902322\t\r\n900657\t\r\n10421\t\r\n" 

But if i have

string test = "902322\t";

Trim() work perfectly. Why this behavior? How i can remove '\t' from string using Trim() method?


Solution

  • String.Trim method deals only with whitespaces at the beginning and the end of the string

    So you should use String.Replace method

    string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
    string res = test.Replace("\t", String.Empty); // res is "902322\r\n900657\r\n10421\r\n"