简体   繁体   中英

How to copy characters in an empty string in C?

I have some strings that look like <12> , where the numbers range from 1 to 100. Now I want to extract the numbers from the string, ie drop the brackets.

This is what I wrote:

char str[5] = "<12>";
char final[5] = "";
for(int i=0;i<strlen(str);i++){
    if(isdigit(str[i])){
        final[i] = str[i];
    }
}

However, I wasn't able to copy the desired number into this empty string and I got nothing printed out. What's the problem?

The problem was on the counter you need an extra counter to add on the end of your array, and you also need add '\0' character. This is just an example

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(){
  char str[5] = "<12>";
  char final[5] = "";
  int x=0;
  for(int i=0;i<strlen(str);i++){
    if(isdigit(str[i])){
      final[x] = str[i]; //here i have changed final counter
      x++;   
    }
  }
  final[x]='\0';

  printf("%s\n", final);

  return 0;
}

Your problem is the fact that you're using the same counter to parse your string and add elements to your new string.

Because of that, the first character you're adding to final is added to the position [1] (the first character that is a digit) instead of being added to position [0]

https://godbolt.org/z/n8bRxW

char *copyDigitsOnly(char *dest, const char *src)
{
    char *tmp = dest;
    if(src && dest)
    {
        while(*src)
        {
            if(isdigit(*src))
            {
                *tmp++ = *src;
            }
            src++;
        }
        *tmp = 0;
    }
    return dest;
}

int main()
{
    char dest[25];
    char *src = "<34>";

    printf("%s\n", copyDigitsOnly(dest,src));
}

I think strtok might be what you are looking for: https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/

You can create an array of delim characters (in this case '<' and '>'), and parse the number into a new string that way.

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