如果我有:如何通過sscanf()獲取字符串中的最後一個數字?
str1 = "str1s2"
str2 = "djfs1d2.3"
我怎樣才能通過的sscanf得到字符串中的最後一個數字()?
我想:
sscanf(str1, "%*[^0-9]%d", &n1);
sscanf(str2, "%*[^0-9]%d", &n2);
但我只得到了第一個數字:
n1 = 1
n2 = 1
如果我有:如何通過sscanf()獲取字符串中的最後一個數字?
str1 = "str1s2"
str2 = "djfs1d2.3"
我怎樣才能通過的sscanf得到字符串中的最後一個數字()?
我想:
sscanf(str1, "%*[^0-9]%d", &n1);
sscanf(str2, "%*[^0-9]%d", &n2);
但我只得到了第一個數字:
n1 = 1
n2 = 1
使用%n
符存儲在掃描處理的字符數,您可以通過串迭代直到scanf失敗。
#include <stdio.h>
int main () {
char str2[] = "2to3";
int span = 0;
int index = 0;
int lastvalue = 0;
int value = 0;
if (1 == sscanf (&str2[index], "%d%n", &value, &span)) {
index += span;
lastvalue = value;
}
while (1 == sscanf (&str2[index], "%*[^0-9]%d%n", &value, &span)) {
index += span;
lastvalue = value;
}
printf ("last value = %d\n", lastvalue);
return 0;
}
太棒了!但爲什麼它不適用於「2to3」或「2to3-2.7」? – alessiovolpe
它打印值= 0 – alessiovolpe
不要有另一種格式來避免這種情況嗎? – alessiovolpe
我個人發現它精心製作了一個錯誤,傾向於只用scanf
模式來表達。我寧願使用一個單獨的循環,迭代從朝開始的字符串的結束,並在最後的多個位置的指針向右:直到你無法得到一個數字
#include <stdio.h>
#include <ctype.h>
// extracts the last positive integral value of string s
// returns...
// on success, the int value scanned
// -1, if the string is null, empty, or not terminated by a number
int extractLastIntegral(const char* s) {
int value = -1;
if (s && *s) { // don't parse null and empty strings
const char *scanstr = s + strlen(s) - 1;
while (scanstr > s && isdigit(*(scanstr-1))) {
scanstr--;
}
sscanf(scanstr,"%d", &value);
}
return value;
}
int main () {
const char* teststrings[] = { "str1s2", "djfs1d2.3", "asdf3asd", "asd", "", NULL};
;
for (const char** teststring=teststrings;*teststring;teststring++) {
printf("string '%s' scans %d\n",*teststring,extractLastIntegral(*teststring));
}
return 0;
}
爲什麼'const char * scanstr = * s? (s + strlen(s) - 1):s;'? – alessiovolpe
如果's'是一個空字符串,'s + strlen(s)-1'會導致'scanptr = s-1',這是非法的。 –
但你是對的 - 閱讀起來有點困難。我修改了答案。 –
迭代。 (可能更容易和更清晰的代碼使用字符指針,並從末尾向後遍歷字符串,直到找到一個數字,然後繼續向後直到找到一個非數字字符,然後從那裏SCANF,雖然)。
char *cp = str1;
int nc;
while(sscanf(cp, "%*[^0-9]%d%n", &n1, &nc) == 1) cp+=nc;
printf("n1: %d\n", n1);
爲什麼選擇投票?這與被接受爲「答案」的後續/同時答案相同。 –
反向然後反向或循環。 – BLUEPIXY
@BLUEPIXY是什麼反向? – alessiovolpe
如果'str3 =「abc1d2e34」;'你想把'34'還是'4'作爲最後的「數字」? –