remove the first and last character of a string in C

Asked

Viewed 183 times

0

I need to make a code where I need to transform a string into an int, but the user can type the number like this: [1234], then I need to remove the first and last character so that it is possible to transform the string into int. Can anyone help me? I’ve tried to do it many ways, but nothing’s right

  • 2

    One possibility is to use the function sscanf to read a string x and ignore the first and last characters of this string and read the integer between them: sscanf(x, "%*c%d%*c", &n);.

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativations worth understanding What is the Stack Overflow and read the Stack Overflow Survival Guide (summarized) in Portuguese.

2 answers

2

You can use the function atoi() library stdlib.h. This function takes the numbers from the string and transforms them into integer. Example:

#include<stdio.h>
#include <stdlib.h>

int main() {
    char str[10] = "123";
    int x = atoi(str);
    printf("%d \n", x);

    char str2[10] = "Teste";
    x = atoi(str2);
    printf("%d \n", x);

    char str3[10] = "Teste321!";
    x = atoi(str3);
    printf("%d", x);
    return 0;
}

Exit:

123
0
321

0


Use the table as Natan replies.

This excerpt ((char str[10] = "Teste321!")) didn’t work here with me so I did a for.

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char string[10], string_sem_colchete;
    gets(string);

    int numero, i;

    for(i=1; i<strlen(string)-1; i++){
       string_sem_colchete[i-1] = string[i];
    }

    string_sem_colchete[i-1] = '\0';
    numero = atoi(string_sem_colchete);

    printf("Meu numero eh: %d", numero);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.