简体   繁体   中英

How to calculate the numerical value of a string in C

I'm trying to calculate the value a string in C.

I define the string like: char cadena[100] = "Esto es un text securizado$2516"

I need to transform 2516 into an int, I'm actually trying to use atoi() , but I don't know how to separate the string to use the function.

PS: Excuse my English, it's not my native language, I hope you understand what I want to do.

A straightforward approach can look the following way

int number = 0;
char cadena[100] = "Esto es un text securizado$2516";

size_t n = strcspn( cadena, "0123456789" );

if ( cadena[n] ) number = atoi( cadena + n );

Or if the number is already initialized by 0 then you can just write

number = atoi( cadena + n );

In this case zero will be a default value.

You can use strrchr to find the rightmost occurrence of a character. It returns a pointer to that rightmost character, or NULL if it was not found:

char *p;
int n;
if ((p = strrchr(cadena, '$')) != NULL)
    sscanf(p + 1, "%d", &n);

Notice we add 1 to p . This is because p points to the $ character.

And don't use atoi , since it does no error checking. On the other hand, sscanf returns 0 on failure.

#include <stdio.h>

int main(void){
    char cadena[100] = "Esto es un text securizado$2516";
    int value = 0;
    size_t i;

    for(i = 0; cadena[i]; ++i){
        if(1 == sscanf(cadena + i, "%d", &value))//try and get
            break;
    }
    printf("%d\n", value);

    return 0;
}

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