繁体   English   中英

在C编程中提取字符串和数字中的字符串

[英]extract a string number in string of characters and numbers in C programming

有什么功能可以提取字符串中的数字返回数字的字符串?

例如,我有一个字符串: assdf4fdsdf65fsafda5要输出的是数字字符串: 4 65 5 ,而输入字符串的长度assdf4fdsdf65fsafda5

我知道可以提取的方法是:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process
    if (isdigit(*p)) { // Upon finding a digit,
        long val = strtol(p, &p, 10); // Read a number,
        printf("%ld\n", val); // and print it.
    } else { // Otherwise, move on to the next character.
        p++;
    }
}

有没有像char extract(char input,char output){ ... return output;}这样的函数char extract(char input,char output){ ... return output;}谢谢

我不知道有任何可用的功能,但是相当容易实现。 下面的代码假定output至少分配了strlen(input) + 2个字节。 我将留给您删除它可能添加到output的尾随空格。

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

void extract(const char *input, char *output) {
  while (*input) {
    while (*input && !isdigit(*input)) ++input;
    while (isdigit(*input)) *output++ = *input++;
    *output++ = ' ';
  }
  *output = '\0';
}

int main(void) {
  char out[21];
  const char *in = "assdf4fdsdf65fsafda5";

  extract(in, out);
  printf("%s\n", out);
  return 0;
}

输出: 4 65 5

是的,使用atoi可以提取整数no。

int atoi(const char *str)

请参考以下链接

https://stackoverflow.com/a/7842195/4112271

这样的事情怎么样(未经过详尽测试):

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

char non_num[] = " !\"#$%&'()*+,-./;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\^_`abcdefghijklmnopqrstuvwxyz{|}~";

int
main(int argc, char **argv)
{

    char str[]   = "assdf4fdsdf65fsafda5";
    char *next   = str;
    char *strptr = str;

    while( (next = strtok(strptr, non_num)) != NULL )
    {
        printf("%s ", next);
        strptr = NULL;
    }
    printf("\n");


    return(0);


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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