有没有一种方法可以避免字符串中的“\”字符?
//bit array
BitArray b1 = new BitArray(Encoding.ASCII.GetBytes("10101010"));
BitArray b2 = new BitArray(Encoding.ASCII.GetBytes("10101010"));
//Say i perform XOR operation on this
b1 = b1.Xor(b2);
//After the XOR oper the b1 var holds the result
//but i want the result to be displayed as 00000000
//So i convert the bitarray to a byte[] and then to string
byte[] bResult = ToByteArray(b1);
strOutput = Encoding.ASCII.GetString(bResult);
Run Code Online (Sandbox Code Playgroud)
The string strOutput is = "\0\0\0\0\0\0\0\0"
But the desired output is 00000000
Run Code Online (Sandbox Code Playgroud)
其中 ToByteArray 可能是一个简单的方法,如下所示
public static byte[] ToByteArray(BitArray bits)
{
byte[] ret = new byte[bits.Length / 8];
bits.CopyTo(ret, 0);
return ret;
}
Run Code Online (Sandbox Code Playgroud)
替代方案 1:我可以使用正则表达式或 string.replace 忽略 '\' 字符
但是还有其他更好的方法来处理这种情况吗?
您不能只操作二进制行内的值。相反,正如您给出的替代方案,使用正则表达式或字符串替换函数来获取指定的结果集。
例如:通过在代码中调用额外的方法
byte[] bResult = ToByteArray(b1);
strOutput = Encoding.ASCII.GetString(bResult).Replace("\\\"","");
Run Code Online (Sandbox Code Playgroud)
编辑:
我相信在你的情况下我的答案通常会起作用, 但是
0 '\0'
Run Code Online (Sandbox Code Playgroud)
也是 ASCII 字符集(仅在 0 中),这意味着您将获得相同的字符串\0\0\0\0 ..替换为反斜杠字符 (\)
CALL Replace("\0","0")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5283 次 |
| 最近记录: |