简体   繁体   English

如何将特定字符从字符串转换为 int (C)

[英]How to convert a specific character from a string into an int (C)

I'm trying to convert a character from a string into an int.我正在尝试将字符从字符串转换为 int。 I tried this:我试过这个:

int function(char c[]) {
     return (int)c[1];
}

I want to convert only the second character of the string c, which length is only of two.我只想转换字符串 c 的第二个字符,它的长度只有两个。

The problem with this function is that the integer returned is completely different from what I typed.这个 function 的问题是返回的 integer 与我输入的完全不同。

I also tried to compare c[1] and numbers from 0 to 10 (only those numbers need to be converted), but there's a problem with c[1].我还尝试比较 c[1] 和从 0 到 10 的数字(只有那些数字需要转换),但是 c[1] 有问题。

I hope everything is clear enough so you can help me.我希望一切都足够清楚,以便您可以帮助我。

Thanks !!!谢谢 !!!

Answer: I just changed return(int)c[1];答:我刚刚改了return(int)c[1]; into return(int)(c[1]-'0');进入return(int)(c[1]-'0'); and that worked well, at least for me效果很好,至少对我来说

I think you want to convert the char into its ASCII (integer) form.我认为您想将 char 转换为其 ASCII(整数)形式。

printf("The ASCII value of %c = %d\n",i,i);

If you want to convert an integer into char, simply use explicit casting like below:如果要将 integer 转换为 char,只需使用如下显式转换:

char c1 = (char)97;  //c1 = 'a'

Try this out:试试这个:

#include<stdio.h>

int function(char c[]);

int main(void) {
    char characters[3] = {'a','b','c'};

    int a = function(characters);

    printf ("%d",a);

    return 0;
}

int function(char c[]) {
     return (int)c[1];
}

try this:-尝试这个:-

int function(char c[]) {
    int x=0;
    try {
        x = Integer.parseInt(String.valueOf(c[1]));
    }catch (NumberFormatException e){
        x=c[1];
    }
    return x;
}

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

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