异或字符串在C# [英] XOR-ing strings in C#
问题描述
最近,我开始用C#玩弄,我试图理解为什么下面的代码不会编译。在有错误注释的行,我得到:
无法隐式转换类型'诠释'到'字符。显式转换出口(是否缺少强制转换?)
块引用>
我试图做一个简单的异或操作有两个字符串。
{
的char [] = charAArray a.ToCharArray> ();
的char [] = charBArray b.ToCharArray();
的char []结果=新的char [6];
INT LEN = 0;
//设置长度要短串
的长度,如果(则为a.length> b.length个)
LEN = b.length个 - 1;
,否则
LEN =则为a.length - 1;
的for(int i = 0; I< LEN,我++){
结果[I] = charAArray [I] ^ charBArray [I] //错误这里
}
返回新的字符串(结果);
}
解决方案您正在做一个
XOR
2字符。因为没有数据丢失这将做一个隐式类型转换为INT
为您服务。但是,把从INT
回字符
将需要你提供一个明确的转换。
您需要显式地转换您的
INT
到字符
为结果[I]
:结果[I] =(字符)(charAArray [I] ^ charBArray [I]);
I recently started playing around with C#, and I'm trying to understand why the following code doesn't compile. On the line with the error comment, I get:
Cannot implicitly convert type 'int' to 'char'. An explicit conversion exits (are you missing a cast?)
I'm trying to do a simple XOR operation with two strings.
public string calcXor (string a, string b) { char[] charAArray = a.ToCharArray(); char[] charBArray = b.ToCharArray(); char[] result = new char[6]; int len = 0; // Set length to be the length of the shorter string if (a.Length > b.Length) len = b.Length - 1; else len = a.Length - 1; for (int i = 0; i < len; i++) { result[i] = charAArray[i] ^ charBArray[i]; // Error here } return new string (result); }
解决方案You are doing an
xor
on 2 characters. This will do an implicit type conversion toint
for you since there is no data loss. However, converting back fromint
tochar
will need you to provide an explicit cast.You need to explicitly convert your
int
to achar
forresult[i]
:result[i] = (char) (charAArray[i] ^ charBArray[i]);
这篇关于异或字符串在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!