Remove CRLF from string C#

Viewed 14087

I'm trying to convert this VBA fonction that remove CRLF from string to a C# function that must do the same result

Private Function RemoveCRLFFromString(ByVal pString As Variant) As String
Dim i As Integer
Dim c As String * 1

 If IsNull(pString) Then
    RemoveCRLFFromString = ""
 Else
    For i = 1 To Len(pString)
        c = Mid$(pString, i, 1)
        If Asc(c) <> 10 And _
           Asc(c) <> 13 Then
           RemoveCRLFFromString = RemoveCRLFFromString & c
        End If
    Next i
 End If


 RemoveCRLFFromString = Left$(RemoveCRLFFromString, 9)

End Function

So far I have come up with:

public static string RemoveCRLFFromString(string pString )
{
    if(String.IsNullOrEmpty(pString))
    {
        return pString ;
    }
    string lineSep = ((char) 0x2028).ToString();
    string paragraphSep = ((char)0x2029).ToString();

    return pString.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(lineSep, string.Empty).Replace(paragraphSep, string.Empty);
}

But it's not achieving the same result, can someone help me adjust my C# function to match the same result as the VBA version?

2 Answers

You are missing the null check (the original function returns an empty string in that case) and also you forgot the Left$ which trims the string size.

public static string RemoveCRLFFromString(string pString)
{
    //Return empty string if null passed
    if(pString == null)
        return ""; 

    //Remove carriage returns
    var str = pString.Replace("\n","").Replace("\r",""); 

    //If len is more than 9 chars trim it
    return str.Length > 9 ? str.Substring(0, 9) : str;
}

The VBA function is unnecessarily complicated. It can be simplified to:

Private Function RemoveCRLFFromString(ByVal pString As Variant) As String
    Dim s As String

    s = Nz(pString)  ' Available in Access VBA, in Excel you'd need a null check
    s = Replace(s, vbCr, "")
    s = Replace(s, vbLf, "")

    RemoveCRLFFromString = Left(s, 9)
End Function

Once the useless complexity is gone, the translation to C# is straightforward and left as an exercise to the reader. Note:

  • Nz(...) becomes ... ?? ""
  • Replace(...) becomes ....Replace(...)
  • Left becomes Truncate, which isn't a built-in method but can be implemented easily with a length check.

Oh, and since your method does more than removing CR and LF (it also truncates the string), its name should be changed.

Related