[英]How to get the last char from a string
我想在列表字符串中獲取重量和 object(在此示例中,我想獲取 integer 501 和字符串“kg bag of sugar”。但我不知道如何在 Z157DB7ZDF5300235672E851C 之后字符串。確實知道 integer 之前和之后有多少個空格(這就是為什么我做 +3 的原因,因為 integer 之前有 2 個空格,最后有 1 個空格)。我的代碼中有分段錯誤。
這是我正在嘗試做的一個例子。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* get the weight and the object */
int main(void) {
char line[50] = " 501 kg bag of sugar"; //we don't know how many char after integer
char afterint[50];
long int weight, weight2;
int lenofint;
sscanf(line, "%ld", &weight);
weight2 = weight;
while (weight2 != 0) {
weight2 = weight2 / 10;
lenofint++;
}
afterint[0] = line[lenofint + 3]; // +3 since there are 2 spaces before integer and 1 space at the end
//printf("%c", afterint);
for (int j = 1; j < (strlen(line) - lenofint - 3); j++) {
afterint[j] = afterint[j] + line[j + lenofint + 3];
}
printf("%s", afterint);
}
停止硬編碼偏移,讓這對自己很難。 scanf
系列函數包括一個選項%n
,它將告訴您在掃描中已經處理了多少個字符。 從那里您可以跳過空白並繼續您的 label 的其余部分。
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[50] = " 501 kg bag of sugger";
long int weight;
int count;
if (sscanf(line, "%ld%n", &weight, &count) == 1)
{
char *suffix = line+count;
while (*suffix && isspace((unsigned char)*suffix))
++suffix;
puts(suffix);
}
}
Output
kg bag of sugger
作為獎勵,通過使用這種方法,您還可以獲得錯誤檢查。 請注意檢查sscanf
的返回結果,它指示成功的參數解析次數。 如果不是1
,則意味着緩沖區中的任何內容 position 都無法成功解析為%ld
(long int),因此 rest 毫無意義。
您可以使用strtol()
讀取數字並獲取指向字符串中數字后點的指針。 然后它會指向一kg bag of sugar
。 這樣您就不需要從數字中進行任何反算。 在任何情況下,數字都可能有前導零等,因此無論如何您都無法從數值中知道字符的長度。
然后跳過從strtol
獲得的指針中的空格。
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char *foo = " 501 kg bag of sugar";
char *thing = NULL;
int weight = 0;
weight = strtol(foo, &thing, 10);
while (isspace(*thing)) {
item++;
}
printf("weight: %d thing: %s\n", weight, thing);
}
或者,我想你可以做類似sscanf(foo, "%d %100c", &weight, buffer);
獲取數字和以下字符串。 (我會讓你選擇一個比%100c
更明智的轉換。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.