Convert string data to integer data and extract integer data in C language

Method 1: Use the atoi function in the library to convert the character type to an integer type, and then the integer type can be extracted.

#include<stdio.h>
#include<string.h>
int main()
{
    char a[15];//定义char类型 
    int x; //定义int整型 
    printf("请输入一个字符串:  ");
    gets(a);
    printf("字符串为:  %s\n",a);
    x=atoi(a);//调用库中的atoi函数,将数据转为整型
    printf("a的整型为: %d",x);
    return 0; 
     
}

As can be seen from Figure 2, this method has certain limitations. If you only want to extract the integer data in this string, for example, for the string "123abc", you can directly extract 123, but for " abc123", the atoi function will directly return 0 after recognizing non-integer data, and cannot extract 123, so we can first convert "abc123" to "123", and then use atoi to convert "123" to 123 to achieve up.

Method Two:

#include<stdio.h>
#include<string.h>
char Str_be_int(char *str,char *num)
{
    int i=0,j=0;

    int len = strlen(str);
    for(i=0;i<len;i++)
    {
        if(str[i]>='0' && str[i]<='9')
        {
            num[j] = str[i];
            j++;
        }
    }
    
    
}
int main()
{
    char a[15],b[15];//定义char类型 
    int x; //定义int整型 
    printf("请输入一个字符串:  ");
    gets(a);
    printf("字符串为:  %s\n",a);
    Str_be_int(a,b);
    printf("%s\n",b); 
    x=atoi(b);//调用库中的atoi函数,将数据转为整型
    printf("字符串的整型为: %d",x);
    return 0; 
     
}

Idea: The Str_be_int() function extracts the string "123", and the atoi() function converts it into an integer.

If there are deficiencies, look forward to your corrections.

Guess you like

Origin blog.csdn.net/qq_62262788/article/details/128536457