1

我是这方面的初学者,所以我希望我能找到一些解决方法

如何读取或复制或选择字符串中特定字符后的数字值?

假设我有一个字符串:

“ans=(提交的任何数字)”

如何仅选择(提交的任何数量)部分?

假设提交的值是 999.. 因此字符串将是“ans=999”.. 在这种情况下如何复制 999?我想稍后将值用于 atoi()

先感谢您。非常感谢这里的一些帮助

4

4 回答 4

3

给定表单中的字符串ans=999,您通常会使用strchr()来查找=.

所以,

char *arg = strchr(string, '=');
if (arg != NULL)
{
    arg++; /* we want to look at what's _after_ the '=' */

    printf("arg points to %s\n", arg);
}
else
    /* oops: there was no '=' in the input string */ ;

应该打印

arg points to 999
于 2013-08-13T21:48:57.110 回答
2

strchr函数返回从指定字符的第一个实例开始的字符串

于 2013-08-13T21:46:47.753 回答
1

您可以使用strchr实现它:

返回指向 C 字符串 str 中第一次出现的字符的指针。

您只需要找到角色=并获取之后的所有内容:

#include <string.h>  // For strchr

char* ans = "ans=999";          // Your string with your example
char* num = strchr( ans, '=' ); // Retrieve a pointer to the first occurence found of =

if ( num != NULL )              // Test if we found an occurence
{
    arg++;                      // We want to begin after the '='

    printf( "The number : %s", arg ); // For example print it to see the result
}
else
{
    // Error, there is no = in the string
}
于 2013-08-13T21:55:20.203 回答
0

一种方法是使用上面提到的 strchr。这指向该字符在字符串中的第一个位置。但是如果你知道你每次都有“ans=#”作为格式。为什么要在 strchr 上浪费 CPU 时间?更快的方法是 sscanf。一个例子是:

char *string = "ans=999";
int number, scanned;

scanned = sscanf(string,"ans=%d",&number);

if(scanned < 1)
printf("sscanf failure\n");

这样做是抓住字符串中的 999 并将其编号。sscanf 还返回成功扫描了多少数字,因此您可以稍后将其用于错误检查等。

于 2013-08-13T22:06:56.867 回答