[英]Adding int values to char array ASCII value C# & JAVA
in Java you can easily add an int value to a char array without defining it like this 在Java中,您可以轻松将int值添加到char数组中,而无需像这样定义它
String name = " maisam is my name ";
char[] arr = name.toCharArray();
for (int i = 0; i < arr.length; i++) {
arr[i] += 100;
}
but in c# you need to mention (char) while adding value 但是在C#中,您需要在增加价值时提及(char)
string name = " maisam is my name ";
char[] arr = name.ToCharArray();
for (int i = 0; i < arr.Length; i++) {
arr[i] += (char) 100;
}
I tried both ways in Java, worked perfectly , no error but in c# it gave me an error, why is that ? 我在Java中尝试了两种方法,都运行良好,没有错误,但是在C#中却给了我一个错误,为什么呢? I searched everywhere didn't find any explanation regarding it !
我到处搜索,没有找到任何解释!
This is more about what's going on behind the scenes rather than a syntax difference. 这更多是关于幕后情况,而不是语法差异。 You cast the same way in Java as you do in C#, but you just don't need to in this piece of Java code.
您在Java中的转换方式与在C#中相同,但是您不需要在这段Java代码中进行转换。 In Java it automatically casts the int to a char type.
在Java中,它会自动将int强制转换为char类型。 But C# works differently, you must cast the value.
但是C#的工作原理有所不同,您必须强制转换值。 It seems as though C# is a bit more strongly typed than Java.
似乎C#比Java具有更强的类型。
this should work. 这应该工作。 c# implicitly casts char to int, but not int to char, so you have to cast the added int value to char before assigning to char array..
c#隐式将char转换为int,但不将int转换为char,因此在分配给char数组之前,必须将添加的int值转换为char。
string name = " maisam is my name ";
char[] arr = name.ToCharArray();
for (int i = 0; i < arr.Length; i++) {
arr[i] = (char)(arr[i] + 100);
}
EDIT: the code arr[i] += (char)100;
编辑:代码
arr[i] += (char)100;
also works fine. 也可以。 The above code is just an elaboration of the same code.
上面的代码只是对相同代码的阐述。
In simple words, there is no implicit conversion from int
to char
in C#
简单来说,
C#
没有从int
到char
隐式转换。
What you will have for C#
int
are, C#
int
是
int -> long , float, double, or decimal
See the other availability from this source . 请参阅此来源中的其他可用性。
Since you don't have an implicit conversion like 由于您没有像这样的隐式转换
char c = 100 ;
But should use Explicit conversion 但是应该使用显式转换
char c = (char) 100 ;
Also here it is : C# char
( source ) 同样在这里是:
C# char
( source )
Conversions 转换次数
A char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal.
字符可以隐式转换为ushort,int,uint,long,ulong,float,double或小数。 However, there are no implicit conversions from other types to the char type.
但是,没有从其他类型到char类型的隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.