2012-10-23 187 views
2

我有一个整数值的字符串。例如20 200 2000 21 1如何从字符串中删除第一个字c

我想删除第一个单词(在这种情况下为20)。任何想法如何做到这一点?

我想过用类似...

sscanf(str, "/*somehow put first word here*/ %s", str); 

回答

5

如何

char *newStr = str; 
while (*newStr != 0 && *(newStr++) != ' ') {} 
+0

你可以只检查0摆脱strlen的考验!= *中newstr。 –

+0

更好,谢谢。 – DrummerB

1

你可以跳过所有字符的第一空间,然后跳过空间本身,就像这样:

char *orig = "20 200 2000 21 1"; 
char *res; 
// Skip to first space 
for (res = orig ; *res && *res != ' ' ; res++) 
    ; 
// If we found a space, skip it too: 
if (*res) res++; 

此代码段打印200 2000 21 1link to ideone)。

4

您可以使用strchr(),这将设置str到第一个空格之后的子字符串,或者如果没有空格,则将其保留;

char *tmp = strchr(str, ' '); 
if(tmp != NULL) 
    str = tmp + 1; 
0

我发现的最简单,最优雅的方式是做这样的事情

int garbageInt; 
    sscanf(str, "%d %[^\n]\n",&garbageInt,str);