【问题标题】:String Trim Spaces doesn't work字符串修剪空间不起作用
【发布时间】:2012-08-02 13:20:55
【问题描述】:

我的字符串有问题。 字符串是这样的:

string something = "  whatever and something else  ";

现在我正在尝试像这样摆脱开头和结尾的空格:

something = something.Trim();

但这没有用,我也试过这个:

something = something.TrimStart();
something = something.TrimEnd();

还有这个:

something = something.TrimStart(' ');
something = something.TrimEnd(' ');

还有这个:

int lineLength = line.Length;
string LastCharacter = line.Remove(lineLength - 1);
while (LastCharacter == " ")
{
   line = line.Remove(lineLength - 1);
   lineLength = line.Length;
   LastCharacter = line.Remove(lineLength - 1);
}

字符串超出 RichTextBox。

现在我认为这可能是文本格式或其他问题(我在德国)。

提前谢谢你, tietze111

【问题讨论】:

  • 您使用什么语言? The string is like this: ...“喜欢”是什么意思?那是您拥有的 exact 字符串吗?如果不是,你从哪里得到字符串,当转换为 int 时每个字符的值是多少?
  • .Trim() 应该按您的预期工作,您使用它是正确的。问题在于您的字符串中包含的文本。
  • 感谢您的回答,文本来自richTextBox,对不起,我忘记了语言,它是C#

标签: c# string space trim spaces


【解决方案1】:

这里有一些东西会撕掉所有的空白:

 string something = " whatever    ";
 List<char> result = something.ToList();
 result.RemoveAll(c => c == ' ');
 something = new string(result.ToArray());

好的,试试这个仅用于开始和结束的修剪:

  static string TrimWhitespace(string theString)
    {
        theString = "  some kind of string example ";
        theString = theString.TrimEnd();
        theString = theString.TrimStart();
        // MessageBox.Show(theString, "");
        return theString;
    }

【讨论】:

  • 对不起,我只想去掉开头和结尾的空格。
  • 我看到您的代码使用了相同的 TrimEnd 和 TrimStart 函数。我刚刚测试了我发布的内容,它确实有效。如果没有,请告诉我(小组)。
  • 感谢您的回答,但我认为这不会奏效,因为我已经尝试过几乎相同的方法。
  • 对不起,是我的错,Trim()后面加了一个空格,所以不能正常工作,谢谢解答!
猜你喜欢
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 2013-02-01
  • 2016-06-23
  • 2020-10-26
  • 2012-03-21
  • 2013-07-11
  • 1970-01-01
相关资源
最近更新 更多