如何在java中的char数组中添加整数元素

时间:2021-01-04 15:59:13
String st="1a2b3j4";

char ar[]=st.toCharArray();

int sum=ar[0]+ar[2];//how to add the numbers

when i try to add its taking ASCII values

当我尝试添加其采用ASCII值

how to convert chat'1' to integer

如何将chat'1'转换为整数

3 个解决方案

#1


2  

You just must convert the character to String and then use something like this:

您只需将字符转换为String,然后使用以下内容:

int sum = Integer.parseInt(stringNum1) + Integer.parseInt(stringNum2);

#2


0  

If you want to convert character ASCII numeric value, just cast your char as an int

如果要转换字符ASCII数值,只需将char转换为int

like char character = arr[0];    
int asciiValue = (int) character;

#3


0  

Are you looking for this?

你在找这个吗?

String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
    sum += (ar[i] - '0');
}
System.out.println(sum); // prints 167 (1 + 49 + 2 + 50 + 3 + 58 + 4)

If you want to consider the ASCII value for the alphabets but the numeric digits itself, then you can try as following.

如果要考虑字母的ASCII值而不是数字本身,那么您可以尝试如下。

String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
    if (ar[i] >= '0' && ar[i] <= '9') {
        sum += (ar[i] - '0');
    } else {
        sum += ar[i];
    }
}
System.out.println(sum); // prints 311 (1 + 97 + 2 + 98 + 3 + 106 + 4)

Note that, ASCII values for 1,a,2,b,3,j,4 are 49,97,50,98,51,106,52.

注意,1,a,2,b,3,j,4的ASCII值是49,97,50,98,51,106,52。

#1


2  

You just must convert the character to String and then use something like this:

您只需将字符转换为String,然后使用以下内容:

int sum = Integer.parseInt(stringNum1) + Integer.parseInt(stringNum2);

#2


0  

If you want to convert character ASCII numeric value, just cast your char as an int

如果要转换字符ASCII数值,只需将char转换为int

like char character = arr[0];    
int asciiValue = (int) character;

#3


0  

Are you looking for this?

你在找这个吗?

String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
    sum += (ar[i] - '0');
}
System.out.println(sum); // prints 167 (1 + 49 + 2 + 50 + 3 + 58 + 4)

If you want to consider the ASCII value for the alphabets but the numeric digits itself, then you can try as following.

如果要考虑字母的ASCII值而不是数字本身,那么您可以尝试如下。

String st = "1a2b3j4";
char ar[] = st.toCharArray();
int sum = 0;
for (int i = 0; i < ar.length; i++) {
    if (ar[i] >= '0' && ar[i] <= '9') {
        sum += (ar[i] - '0');
    } else {
        sum += ar[i];
    }
}
System.out.println(sum); // prints 311 (1 + 97 + 2 + 98 + 3 + 106 + 4)

Note that, ASCII values for 1,a,2,b,3,j,4 are 49,97,50,98,51,106,52.

注意,1,a,2,b,3,j,4的ASCII值是49,97,50,98,51,106,52。