Reputation: 87
"How do I do this? "
Let's say I have this string. How do I remove only one space from the end? The code shown below gives me an error saying the count is out of range.
string s = "How do I do this? ";
s = s.Remove(s.Length, 1);
Upvotes: 1
Views: 228
Reputation: 1045
Another way to do it is;
string s = "How do I do this? ";
s=s.SubString(0,s.Length-1);
Additional :
If you would like do some additional checking for the last character being a space or anything,you can do it in this way;
string s = "How do I do this? a";//Just for example,i've added a 'a' at the end.
int index = s.Length - 1;//Get last Char index.
if (index > 0)//If index exists.
{
if (s[index] == ' ')//If the character at 'index' is a space.
{
MessageBox.Show("Its a space.");
}
else if (char.IsLetter(s[index]))//If the character at 'index' is a letter.
{
MessageBox.Show("Its a letter.");
}
else if(char.IsDigit(s[index]))//If the character at 'index' is a digit.
{
MessageBox.Show("Its a digit.");
}
}
This gives you a MessageBox with message "Its a letter".
One more thing that might be helpful,if you want to create a string with equal no. of spaces between each word,then you can try this.
string s = "How do I do this? ";
string[] words = s.Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries);//Break the string into individual words.
StringBuilder sb = new StringBuilder();
foreach (string word in words)//Iterate through each word.
{
sb.Append(word);//Append the word.
sb.Append(" ");//Append a single space.
}
MessageBox.Show(sb.ToString());//Resultant string 'sb.ToString()'.
This gives you "How do I do this? " (equal spaces between words).
Upvotes: 0
Reputation: 560
This is a little safer, just in case the last character is not a space
string s = "How do I do this? ";
s = Regex.Replace(s, @" $", "")
Upvotes: 1
Reputation: 3381
You have to write something in the lines of
string s = "How do I do this?
s = s.Remove(s.Length-1, 1);
Reason being that in C# when referring to indexes in arrays the first element is always at position 0 and end at Length - 1. The Length generally tells you how long a string is but doesn't map to the actual array index.
Upvotes: 0
Reputation: 39767
Just do a substring from the first character (chars are 0-based in string) and get number of chars less the string length by 1
s = s.Substring(0, s.Length - 1);
Upvotes: 1
Reputation: 33381
The indexing in C# are zero-based.
s = s.Remove(s.Length - 1, 1);
Upvotes: 2
Reputation: 11938
You just have to use this instead :
string s = "How do I do this? ";
s = s.Remove(s.Length-1, 1);
As stated here:
Remove(Int32) Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
In an array, positions range from 0 to Length-1, hence the compiler error.
Upvotes: 3