2015-11-04 108 views
-2

我有任務計算隨機字中的字母數,直到輸入「End」。我不允許使用strlen();功能。這是我目前的解決方案:如何在不使用strlen的情況下計算字符串的字符數

#include <stdio.h> 
#include <string.h> 

int stringLength(char string[]){ 
    unsigned int length = sizeof(*string)/sizeof(char); 
    return length; 
} 

int main(){ 
    char input[40]; 
     
    while (strcmp(input, "End") != 0) { 
        printf("Please enter characters.\n"); 
        scanf("%s", &input[0]); 
        while (getchar() != '\n'); 
        printf("You've entered the following %s. Your input has a length of %d characters.\n", input, stringLength(input)); 
    } 
} 

stringLength值不正確。我究竟做錯了什麼?

+0

'* string'是單個字符,所以'的sizeof(*串)'是一個字符,這始終是'1'的大小。 – Barmar

+0

您需要編寫一個循環來計算字符,直到它到達空終止符。 – Barmar

+3

指針不是數組不是指針。 – Olaf

回答

2

%n說明符也可用於捕獲字符數。
使用%39s將防止將太多字符寫入數組input[40]

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char input[40] = {'\0'}; 
    int count = 0; 

    do { 
     printf("Please enter characters or End to quit.\n"); 
     scanf("%39s%n", input, &count); 
     while (getchar() != '\n'); 
     printf("You've entered the following %s. Your input has a length of %d characters.\n", input, count); 
    } while (strcmp(input, "End") != 0); 

    return 0; 
} 

編輯糾正@chux指出的缺陷。
使用" %n來記錄前導空格和%n"記錄總字符,這應記錄前導空格的數量和解析的總字符。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) 
{ 
    char input[40] = {'\0'}; 
    int count = 0; 
    int leading = 0; 

    do { 
     printf("Please enter characters. Enter End to quit.\n"); 
     if ((scanf(" %n%39s%n", &leading, input, &count)) != 1) { 
      break; 
     } 
     while (getchar() != '\n'); 
     printf("You've entered %s, with a length of %d characters.\n", input, count - leading); 
    } while (strcmp(input, "End") != 0); 

    return 0; 
} 

EDIT stringLength()函數返回長度

int stringLength(char string[]){ 
    unsigned int length = 0; 
    while (string[length]) {// true until string[length] is '\0' 
     length++; 
    } 
    return length; 
} 
+0

偉大的解決方案!你還可以爲其他人描述的方式添加一個解決方案嗎? :-) – PeterPan

+1

'「%n」'會報告被解析的'char'的數量,包括前導的空格。嘗試輸入'「123」'和輸出將會說輸入是長度爲4的'「123」'。 – chux

+1

對我來說看起來不錯。沒有看到新的問題。 – chux

1

請注意,sizeof評估編譯時間。所以它不能用於確定運行時間中字符串的長度。

字符串的長度是直到遇到空字符時的字符數。因此字符串的大小比字符的數量多一個。這個最終的空字符被稱爲,終止空字符

因此,要知道運行時字符串的長度,必須計算字符數,直到遇到空字符。

用C語言編程很簡單;我把這個留給你。

相關問題