我正在尝试从ASP.NET textarea中保留字符串。我需要去除回车换行符,然后将剩下的东西拆分成50个字符的字符串数组。
到目前为止我有这个
var commentTxt = new string[] { };
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb != null)
commentTxt = cmtTb.Text.Length > 50
? new[] {cmtTb.Text.Substring(0, 50), cmtTb.Text.Substring(51)}
: new[] {cmtTb.Text};
它工作正常,但我没有剥离CrLf字符。我该如何正确地做到这一点?
答案 0 :(得分:98)
你可以使用正则表达式,是的,但是一个简单的string.Replace()可能就足够了。
myString = myString.Replace("\r\n", string.Empty);
答案 1 :(得分:40)
.Trim()函数将为您完成所有工作!
我正在尝试上面的代码,但是在“修剪”功能之后,我发现它甚至在它到达替换代码之前都是“干净的”!
String input: "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."
答案 2 :(得分:21)
更好的代码:
yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);
答案 3 :(得分:20)
这会将字符串拆分为新行字符的任何组合,并将它们与空格连接,假设您确实需要新行所在的空间。
var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));
Console.Write(newString);
// prints:
// the quick brown fox jumped over the box and landed on some rocks.
答案 4 :(得分:2)
试试这个:
private void txtEntry_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string trimText;
trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
this.txtEntry.Text = trimText;
btnEnter.PerformClick();
}
}
答案 5 :(得分:1)
假设你想用某事替换换行符,以便像这样:
the quick brown fox\r\n
jumped over the lazy dog\r\n
不会像这样结束:
the quick brown foxjumped over the lazy dog
我会做这样的事情:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
如果语法不完美,我道歉;我现在不在使用C#的机器上。
答案 6 :(得分:1)
这是一个完美的方法:
请注意 Environment.NewLine 适用于 Microsoft 平台。
除上述内容外,您还需要在单独的功能中添加 \ r 和 \ n !
以下是支持您是否在 Linux,Windows或Mac 上键入的代码:
var stringTest = "\r Test\nThe Quick\r\n brown fox";
Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");
stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();
答案 7 :(得分:0)
使用:
string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));