如何在字符串中的特定字符后选择/读取/复制值

时间:2013-08-13 21:42:41

标签: c

我是这方面的初学者,所以我希望我能为这个

找到一些解决方法

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

假设我有一个字符串:

  

“ans =(提交的任何号码)”

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

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

的值

提前谢谢你。真的很感激一些帮助

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

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

答案 2 :(得分: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
}

答案 3 :(得分:0)

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

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

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

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

这样做是抓住字符串中的999并将其放入数字。 sscanf还会返回成功扫描的数量,因此您可以稍后使用它来进行错误检查等等。