2014-02-10 42 views
0

我剛剛開始C編程,並試圖做一個練習,其中您將(主)中的幾個字符串讀入一個函數,在該函數中可以找到每個字符串中的單詞和字符長度,主)在每個字符串中打印字數和字符數。我不完全確定如何做到這一點。例如..如何將多個字符串傳遞到函數來處理

#include <stdio.h> 
void convert(char s[]), int counts[]); 

int main(void) 
{ 
    char text1[] = "this IS a String 4 you."; 
    char text2[] = "This sample has less than 987654321 leTTers." 
    char text3[] = "Is thIs a string? (definitely)" 


void convert(char s[]), int counts[]) 
{ 
    """code that reads each string and counts words and characters returning 
    an array of characters like a[] = {3,5} each number telling how many words 
    and characters the string has""" 
} 
+0

如何爲函數添加更多的輸入參數? – moeCake

+0

先刪除額外的''''。 – herohuyongtao

+0

爲什麼?創建函數計算一個字符串中的單詞(返回一個int)。在一個字符串中創建另一個計數字符(也返回一個int)。然後循環你的字符串並調用這些函數。 – LumpN

回答

0

而不是

char text1[] = "this IS a String 4 you."; 
char text2[] = "This sample has less than 987654321 leTTers." 
char text3[] = "Is thIs a string? (definitely)" 

你可以寫

char* texts[] = { "this IS a String 4 you.", 
        "This sample has less than 987654321 leTTers.", 
        "Is thIs a string? (definitely)", 
        NULL }; 

你的函數看起來是這樣的(C99)

void convert(char* s[], int counts[]) 
{ 
    for (int i = 0; s[i] != NULL; ++i) 
    { 
    ...do something with s[i]... 
    } 
0

使用二維數組。像

#include <stdio.h> 
void convert(char s[]), int counts[]); 

int main(void) 
{ 
    char text1[][] = {"this IS a String 4 you.","This sample has less than 987654321 leTTers.","Is thIs a string? (definitely)",NULL}; 

} 

void convert(char s[][], int counts[]) 
{ 
    You can access here s[0][0],s[1][0],s[2][0],... etc. 
    """code that reads each string and counts words and characters returning 
    an array of characters like a[] = {3,5} each number telling how many words 
    and characters the string has""" 
} 
0
void convert(char s[], int counts[]) 
{ 
    int l=0, w=0; 

    for(;s[l]!='\0';l++) 
     if(l!=0 && s[l]==' ' && s[l-1]!=' ') 
      w++;    

    if(s[l-1]!=' ') 
     w++; 

    counts[0]=l; 
    counts[1]=w; 

    return 
} 
0

如果你的目的是要通過一次,你只需修改參數在函數聲明中的所有字符串,並相應地打電話:

void convert(char [], char [], char []); 

int main(void) 
{ 
    char text1[] = "some text1"; 
    char text2[] = "some text2"; 
    char text3[] = "some text3"; 

    convert(text1, text2, text3); 
} 

然而,可能更合理的方式將是存儲指向字符串的指針並使用循環分別調用每個字符串的轉換函數:

void convert(char []); 

int main(void) 
{ 
    char *texts[] = "some text1", "some text2", "some text3"; 

    for (int i = 0; i < 3; i++) 
    { 
     convert(texts[i]); 
    } 
} 

至於單詞/字符數,你有很多選項。僅舉幾例:

  • 按引用傳遞一個值或多個由轉換功能進行修改,並從你的主要功能
  • 返回的計數值(一個或多個)存儲一些結果(S)您的轉換函數以某種形式(結構可能是一個很好的選擇多個值)並將其存儲/
相關問題