[英]Remove a single space from a string
"How do I do this? "
假設我有這個字符串。 如何從末尾僅刪除一個空格? 下面顯示的代碼給我一個錯誤,提示計數超出范圍。
string s = "How do I do this? ";
s = s.Remove(s.Length, 1);
您只需要使用它:
string s = "How do I do this? ";
s = s.Remove(s.Length-1, 1);
如前所述這里 :
Remove(Int32)返回一個新字符串,其中刪除了當前實例中從指定位置開始到最后一個位置的所有字符。
在數組中,位置范圍是0到Length-1,因此會出現編譯器錯誤。
C#中的索引從零開始。
s = s.Remove(s.Length - 1, 1);
只需從第一個字符開始創建一個子字符串(字符串中的字符從0開始),並得到字符數減去字符串長度的1
s = s.Substring(0, s.Length - 1);
以防萬一,以防萬一最后一個字符不是空格
string s = "How do I do this? ";
s = Regex.Replace(s, @" $", "")
你必須寫一些東西
string s = "How do I do this?
s = s.Remove(s.Length-1, 1);
原因是在C#中,當引用數組中的索引時,第一個元素始終位於位置0,並以Length-1結尾。Length通常告訴您字符串有多長時間,但不映射到實際的數組索引。
另一種方法是:
string s = "How do I do this? ";
s=s.SubString(0,s.Length-1);
其他:
如果您想對最后一個字符是否為空格或其他內容做一些額外的檢查,則可以用這種方法進行;
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.");
}
}
這將為您提供一個帶有消息“ Its a letter”的MessageBox。
如果您想創建一個等於no的字符串,那么可能還有另一件事。 每個單詞之間的空格,那么您可以嘗試一下。
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()'.
這將為您提供“我該怎么做?”(單詞之間的空格)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.