0

I have a string with a new line at its end. I cannot choose to remove this newline. Its there in the string already. I wanted to remove the last single quote in this string. I tried using the method given in another post - Trim last character from a string

"Hello! world!".TrimEnd('!');

I get an error when I try to do "Hello! world!".TrimEnd(''');

How do I fix this ?

Community
  • 1
  • 1
Steam
  • 9,368
  • 27
  • 83
  • 122

1 Answers1

5

To trim the new line(s) and last quote(s) from the end of a string, try using .TrimEnd(params char[])

string badText = "Hello World\r\n'";

// Remove all single quote, new line and carriage return characters
// from the end of badText
string goodText = badText.TrimEnd('\'', '\n', '\r');

To remove only the last single quote from a string after removing the possible new line(s), do something like this:

string badText = "Hello World\r\n'";
string goodText = badText.TrimEnd('\n', '\r');
if (goodText.EndsWith("'"))
{
    // Remove the last character
    goodText = goodText.Substring(0, goodText.Length - 1);
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • I think you missed a ) to close the if. But, after doing that. I see an error - the best overloaded match for string.EndsWith(string) has some invalid arguments. – Steam Oct 28 '13 at 01:05
  • @blasto ah, fixed the answer. Use `if (goodText.EndsWith("'"))` – Daniel Imms Oct 28 '13 at 01:08
  • I added the error just now. My code generates a newline after a string and then adds another string to it. I use Environment.newline for this. Also, the last string has a '. I am still not able to get rid of that '. :( – Steam Oct 28 '13 at 01:08
  • @blasto can you put a breakpoint just before you try to trim it then debug and tell me exactly what the string is? If we know what's at the end it should be trivial to remove it. – Daniel Imms Oct 28 '13 at 01:10
  • Thanks. It worked for me. There is no irritating ' at the end now. May I know why you use \r also ? Also, if we had to remove a double quote " with your code, then would "\"" have to be used ? Thanks. – Steam Oct 28 '13 at 01:13
  • 1
    @blasto Here is an explanation http://stackoverflow.com/a/15433225/1156119 you could also use `badText.TrimEnd(Environment.NewLine)` as that defaults to whatever device you're running on. – Daniel Imms Oct 28 '13 at 01:15
  • What about the \r ? Is the badText.TrimEnd(Environment.NewLine) the same as string goodText = badText.TrimEnd('\n', '\r'); ? – Steam Oct 28 '13 at 01:35
  • 1
    @blasto depending on the operating system, it could be `"\r\n"` for Windows or `\n` for Unix. It just future proofs you if you ever want to run it on a Unix system. – Daniel Imms Oct 28 '13 at 03:44