简体   繁体   中英

How to convert char* into string?

How can I convert a char string into various integer? For example:

char *ray = {'2','1','F',' ','2','3'}; //numbers can be any length

How can i convert that line above into:

int num = 21;
int num2 = 23;

How can I convert a char string into various integer?

There are several ways to extract integers from C strings. The first two that come to mind are the sscanf() function and the various string-to-integer conversion functions, such as strtol() . To begin with, however, you need to have an actual string:

char ray[] = {'2','1','F',' ','2','3', '\0' };  /* note the terminator */

or this is 100% equivalent to the previous:

char ray[] = "21F 23";  /* terminator is implicit */

. This works, too ...

char *ray = "21F 23";  /* terminator is implicit */

... even though it is not equivalent. Your example declaration is not of a string, however, because it is not terminated. Moreover, you provide an array initializer for a variable declared to be a pointer. Though pointers and arrays are have a close association, they are very different things.

Given any one of those declarations for ray , you might then do

int num;
int num2;
int result = sscanf(ray, "%d%*[^0-9-]%d", &num1, &num2);

The sscanf() function is like scanf() , but it scans from a string instead of from the standard input. I presume you are familiar with the %d field descriptor for scanning an optionally-signed decimal integer; the bit between the two %d descriptors describes a field that is scanned but not assigned to any variable ( * ), and that consists of a sequence of one or more characters that are not decimal digits or a hyphen / minus sign. Clearly, a scanf-based solution assumes that you know how many numbers to expect in the string (in this case, two).

If you are uncertain how many numbers there will be in the string then it would probably be easier to build your solution around strtol() . That function attempts to convert the initial portion of a string to an integer, and if it is successful, it returns a pointer to the tail of the string following the part that was converted. You can use this to walk through the string, converting each number you find as you go.

Suppose you have any non-digit characters as your delimiters. Then you can try this out->

#include <stdio.h>
#include<string.h>
#define MAX 100

int main() {
    int a,flag=0,len,num_count=0,limit;
    char ray[MAX];
    fgets(ray,MAX-1,stdin);
    len=strlen(ray);
    int *numbers=(int*)calloc(sizeof(int),((len/2)+1));
    for(a=0;a<len;a++){
        if(ray[a]>='0' && ray[a]<='9'){
            flag=1;
            numbers[num_count]=(numbers[num_count]*10)+ray[a]-'0';
        }   
        else{
            if(flag!=0){
                flag=0;
                num_count++;
            }
        }
    }
    limit=(flag==0)?num_count:num_count+1;
    for(a=0;a<limit;a++)
        printf("%d\n",numbers[a]);
    free(numbers);
    return 0;
}
  • Here, I am taking the entire string input into "ray" (input can be like "344h 54j5k45jn").
  • For any string of that format, you can have a maximum of ceiling(ray.length()) numbers. Thus creating an integer array of that size.
  • Now iterating through the string character wise, if I find a continuous block of numbers, I am storing them into the integer array, and if I come across a delimiter, I do not process that.
  • Next just print the integer array.

If any more clarification is needed regarding the logic, please tell me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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