[英]Count and get integers from a string using C
我在自學C編程。 我試圖計算給定字符串中存在的int數量,這些字符串之間用空格隔開。
exp:輸入str =“ 1 2 11 84384 0 212”輸出應為:1、2、11、84384、0、212總int = 6
當我嘗試。 因為我在這里沒有使用正確的方法,所以它為我提供了所有有意義的數字輸出。
我知道在python中我可以使用str.split(“”)函數來快速完成我的工作。
但是我想在C中嘗試類似的方法。嘗試創建自己的split方法。
#include <stdio.h>
#include <string.h>
void count_get_ints(const char *data) {
int buf[10000];
int cnt = 0, j=0;
for (int i=0; i<strlen(data); i++) {
if (isspace(data[i] == false)
buf[j] = data[i]-'0';
j++;
}
printf("%d", j);
}
// when I check the buffer it includes all the digits of the numbers.
// i.e for my example.
// buf = {1,2,1,1,8,4,3,8,4,0,2,1,2}
// I want buf to be following
// buf = {1,2,11,84384,0,212}
我知道這不是解決此問題的正確方法。 一種跟蹤上一個並使用遇到的非空格數字動態創建內存的方法。 但是我不確定這種方法是否有幫助。
您要逐步構建數字,直到遇到空格,然后將其放入數組中。 您可以通過乘以10,然后每次添加下一位數字來完成此操作。
void count_get_ints(const char *data) {
int buf[10000];
int j = 0;
int current_number = 0;
// Move this outside the loop to eliminate recalculating the length each time
int total_length = strlen(data);
for (int i=0; i <= total_length; i++) {
// Go up to 1 character past the length so you
// capture the last number as well
if (i == total_length || isspace(data[i])) {
// Save the number, and reset it
buf[j++] = current_number;
current_number = 0;
}
else {
current_number *= 10;
current_number += data[i] - '0';
}
}
}
我認為strtok
將提供更清潔的解決方案,除非您真的想遍歷字符串中的每個字符。 自從我做C以來已經有一段時間了,所以請原諒下面代碼中的任何錯誤,希望它能給您正確的想法。
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[19] = "1 2 11 84384 0 212";
const char s[2] = " ";
char *token;
int total;
total = 0;
token = strtok(str, s);
while (token != NULL) {
printf("%s\n", token);
total += atoi(token);
token = strtok(NULL, s);
}
printf("%d\n", total);
return 0;
}
您可以通過執行c-'0'
來檢查每個字符的ascii值。 如果介於[0,9]之間,則為整數。 通過使用狀態變量,當您通過檢查給定字符是否為空格而位於整數內時,可以通過忽略空格來跟蹤計數。 另外,您不需要緩沖區, 如果數據大於10,000,並且將緩沖區的末尾寫入pass會發生什么情況,則會發生未定義的行為。 此解決方案不需要緩沖區。
編輯,解決方案現在將打印字符串中的整數
void count_get_ints(const char *data) {
int count = 0;
int state = 0;
int start = 0;
int end = 0;
for(int i = 0; i<strlen(data); i++){
int ascii = data[i]-'0';
if(ascii >= 0 && ascii <= 9){
if(state == 0){
start = i;
}
state = 1;
}else{
//Detected a whitespace
if(state == 1){
count++;
state = 0;
end = i;
//Print the integer from the start to end spot in data
for(int j = start; j<end; j++){
printf("%c",data[j]);
}
printf(" ");
}
}
}
//Check end
if(state == 1){
count++;
for(int j = start; j<strlen(data); j++){
printf("%c",data[j]);
}
printf(" ");
}
printf("Number of integers %d\n",count);
}
我相信,執行此操作的標准方法是使用sscanf
和%n
格式說明符來跟蹤讀取了多少字符串。
您可以從大型數組開始閱讀-
int array[100];
然后,您可以繼續從字符串中讀取整數,直到無法讀取為止或讀完100。
int total = 0;
int cont = 0;
int ret = 1;
while(ret == 1 && total < 100) {
ret = sscanf(input, "%d%n", &array[total++], &cont);
input += cont;
}
total--;
printf("Total read = %d\n", total);
和array
包含所有讀取的數字。
這是演示
使用strtol
示例
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <ctype.h>
int count_get_ints(int output[], int output_size, const char *input) {
const char *p = input;
int cnt;
for(cnt = 0; cnt < output_size && *p; ++cnt){
char *endp;
long n;
errno = 0;
n = strtol(p, &endp, 10);
if(errno == 0 && (isspace((unsigned char)*endp) || !*endp) && INT_MIN <= n && n <= INT_MAX){
output[cnt] = n;
while(isspace((unsigned char)*endp))
++endp;//skip spaces
p = endp;//next parse point
} else {
fprintf(stderr, "invalid input '%s' in %s\n", p, __func__);
break;
}
}
return cnt;
}
int main(void) {
const char *input = "1 2 11 84384 0 212";
int data[10000];
int n = sizeof(data)/sizeof(*data);//number of elements of data
n = count_get_ints(data, n, input);
for(int i = 0; i < n; ++i){
if(i)
printf(", ");
printf("%d", data[i]);
}
puts("");
}
假設您的字符串中沒有任何非數字,則只需計算空格數+ 1即可找到字符串中的整數數,如以下偽代碼所示:
for(i = 0; i < length of string; i++) {
if (string x[i] == " ") {
Add y to the list of strings
string y = "";
counter++;
}
string y += string x[i]
}
numberOfIntegers = counter + 1;
同樣,這將讀取空白之間的數據。 請記住,這是偽代碼,因此語法不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.