I need to remove two characters from the end of the string.
So:
string = "Hello Marco !"
must be
Hello Marco
How can I do it?
You can do:
string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
C# 8 introduced indices and ranges which allow you to write
str[^2..]
This is equivalent to
str.Substring(str.Length - 2, 2)
In fact, this is almost exactly what the compiler will generate, so there's no overhead.
Note that you will get an ArgumentOutOfRangeException if the range isn't within the string.
str[..^2]. 2 doesn't even need to be a constant, so you can also write str[..^"test".Length]I will trim the end for unwanted characters:
s = s.TrimEnd(' ', '!');
To ensure it works even with more spaces. Or better if you want to ensure it works always, since the input text seems to come from the user:
Regex r = new Regex(@"(?'purged'(\w|\s)+\w)");
Match m = r.Match("Hello Marco !!");
if (m.Success)
{
string result = m.Groups["purged"].Value;
}
With this you are safer. A purge based on the fact the last two characters has to be removed is too weak.
Did you check the MSDN documentation (or IntelliSense)? How about the String.Substring method?
You can get the length using the Length property, subtract two from this, and return the substring from the beginning to 2 characters from the end.
For example:
string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
If it's an unknown amount of strings you could trim off the last character by doing s = s.TrimEnd('','!').Trim();
Have you considered using a regular expression? If you only want to allow alpha numeric characters you can use regex to replace the symbols, What if instead of a ! you get a %?