简体   繁体   English

无法在C#中将char数组转换为int值

[英]Can't cast char array into int value in C#

I am making a caesar cipher and am trying to convert the char value of each letter into an int so the shift value can change it. 我正在做一个凯撒密码,并试图将每个字母的char值转换为int值,以便shift值可以更改它。

for (int i = 0; i < plainTextInput.Length; ++i)
{
   chars[i] = ((int)chars[i]) + shiftAmount;         
}

It says it cannot convert int into char. 它说它不能将int转换成char。 How do i fix this problem? 我该如何解决这个问题?

You have to explicitly cast it back: 您必须明确地将其回退:

for (int i = 0; i < plainTextInput.Length; ++i)
{
   chars[i] = (char)(((int)chars[i]) + shiftAmount);         
}

However, you're going to run into trouble pretty quickly once you shift past z . 但是,一旦移过z ,您将很快陷入困境。

By explicitly casting: 通过显式转换:

chars[i] = (char)(((int)chars[i]) + shiftAmount);     

I'd rewrite your loop: 我会重写你的循环:

var enciphered = chars.Select(c => (char)((int)c + shiftAmount)).ToArray();

What are you planning to do if you shift to a non-printable character? 如果您改用不可打印的字符,您打算做什么? Standard Caesar cipher wraps around. 标准凯撒密码环绕。 You should incorporate that. 您应该将其合并。

When I compile that code, I get the following error message: 编译该代码时,出现以下错误消息:

Cannot implicitly convert type 'int' to 'char'. 无法将类型'int'隐式转换为'char'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

Why yes, you are missing a cast: 为什么的,你缺少强制:

chars[i] = (char)(((int)chars[i]) + shiftAmount);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM