如何在字符串中跳过`\ r \n`

Sma*_*boy 5 c#

我正在开发一个简单的转换器,将文本转换为另一种语言,

假设我有两个文本框,在第一个框中输入单词Index并按转换按钮.
我将替换你的文字用urdu语言?????的替代方法,Index但我有一个问题,如果你输入单词index并给出一些空格或给出一些回报然后我得到文本框中的文本c#像这样Index \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n现在我怎么能摆脱这个我想要变得简单Index.
感谢您的回答,如果您有任何疑问,请随时发表评论

Bot*_*000 9

Trim如果新行仅在开头的末尾,请尝试使用该方法:

input = input.Trim();
Run Code Online (Sandbox Code Playgroud)

Replace如果要删除字符串中任何位置的新行,可以使用:

// Replace line break with spaces
input = input.Replace("\r\n", " ");
// (Optionally) Combine consecutive spaces to one space (probalby not most efficient but should work)
while (input.Contains("  ")) { input = input.Replace("  ", " "); }
Run Code Online (Sandbox Code Playgroud)

如果要完全阻止换行,大多数TextBox控件都有类似MultiLine或类似的属性,设置时会阻止输入多行.


Ste*_*eve 5

这应该足以删除Char.IsWhiteSpace定义的空格(空格,换行符等)

string wordToTranslate = textBox1.Text.Trim();
Run Code Online (Sandbox Code Playgroud)

但是,如果您的文本框包含多个单词,那么您应该使用不同的方法

string[] words = textBox1.Text.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
foreach(string wordToTranslate in words)
    ExecTranslation(wordToTranslate);
Run Code Online (Sandbox Code Playgroud)

使用Split with char [] null作为分隔符允许将每个空格标识为有效的单词分隔符


Jak*_*cki 5

input.Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty);

用户Replace从字符串的"内部"删除字符.Trim仅在字符串的开头和结尾删除字符.