views:

817

answers:

3

Hi All, I am trying to persist string from an ASP.NET textarea. I need to strip out the carriage return line feeds and then break up whatever's left into a string array of 50 character pieces.

I have this so far

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};

It works ok, but I am not stripping out the CrLf characters. How do I do this correctly?

Thanks, ~ck in San Diego

+15  A: 

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);
Matt Greer
Better might be `myString.Replace("\r", string.Empty).Replace("\n", string.Empty);`, given that strings in the wild can have lots of CR/LF arrangements.
Craig Stuntz
Would it not be better to use Enviroment.Newline ???
PostMan
Environment.NewLine would be the server's idea of what a new line is. This text is coming from the client, which may use different characters for newlines. Here is an answer that shows what different browsers use for new lines: http://stackoverflow.com/questions/1155678/javascript-string-newline-character/1156388#1156388
Matt Greer
Good point, never thought of that.
PostMan
A: 

Assuming you want to replace the newlines with something so that something like this:

the quick brown fox\r\n
jumped over the lazy dog\r\n

doesn't end up like this:

the quick brown foxjumped over the lazy dog

I'd do something like this:

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);    
}

I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.

Matt McClellan
+2  A: 

This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.

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.
Chris