1

this might be some basic question, but I really can't find an answer: I need to split a string that has two numbers, into two strings in C.

Example:

1->2 into 1 and 2

I'm using strtok, but it takes a series of chars to split, you can't specify a sequence to be the divisor.

I can't use anything outside from ANSI C.

Any help will be appreciated!

How can you flag this as exact duplicate? It's not even close...

4

3 回答 3

5

使用“sscanf()”。不要让别人为你做这件事,因为如果你花几分钟时间来理解它就太容易了,尤其是它的格式说明符字符串细微差别。这里有一个链接就足够了:

http://www.cplusplus.com/reference/cstdio/sscanf/

暗示 : sscanf (source_string,"%d->%d",&num1,&num2);

于 2013-04-22T05:04:06.330 回答
2

好吧,这里有一些东西可以帮助您入门:

const char *FindSubString( const char *sub, const char *src )
{
  // Loop through the source string
  while(*src++)
  {
    // Only check for matching character in beginning of sub sequence
    if(*src == *sub)
    {
      return src;
    }
  }
}

这只是找到指向子序列中第一个匹配字符的指针和源字符串。我相信你可以在内部循环中收集一些东西,检查字符串是否与sub字符串中接下来的几个字符匹配src

于 2013-04-22T05:18:35.093 回答
1

这是一种蛮力方法。只适合快速修复。

#include <stdlib.h>
#include <ctype.h>

void extract_2_numbers (char *str, int *a, int *b) {
  *a = atoi (str);
  while (isdigit(*str)) str++;
  while (!isdigit(*str)) str++;
  *b = atoi (str);
}

int main () {
  int x, y;
  char *string = "12--->24";

  extract_2_numbers (string, &x, &y);
  printf ("%d\t%d\n", x, y);
  return 0;
}

打印此输出:

12    24
于 2013-04-22T06:38:27.337 回答