我试图将这个将CRLF从字符串中移除的VBA函数转换为必须执行相同结果的C#函数
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
到目前为止,我已提出:
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);
}
但它没有达到相同的结果,有人可以帮我调整我的C#功能以匹配与VBA版本相同的结果吗?
答案 0 :(得分:3)
您缺少空检查(原始函数在这种情况下返回一个空字符串),而且您忘记了修剪字符串大小的Left$
。
public static string RemoveCRLFFromString(string pString)
{
//Return empty string if null passed
if(pString == null)
return "";
//Remove carriage returns
var str = string.Replace("\n","").Replace("\r","");
//If len is more than 9 chars trim it
return str.Length > 9 ? str.Substring(0, 9) : str;
}
答案 1 :(得分:2)
VBA功能不必要地复杂化。它可以简化为:
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
一旦无用的复杂性消失,对C#的翻译很简单,并留给读者练习。注意:
Nz(...)
变为... ?? ""
Replace(...)
变为....Replace(...)
Left
变为Truncate,这不是内置方法,但可以通过长度检查轻松实现。哦,因为你的方法更多比删除CR和LF(它也截断字符串),所以应该改变它的名字。