2016-09-19 68 views
-1

我要求用戶輸入一個字符串。我想用大寫字母輸出每個單詞的第一個字母。不保存到數組的字符

實施例: barack hussein obama =>BHO

目前,這是我的嘗試:

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

int main(void){ 
    string user_name = GetString(); 

    int word_counter = 0; 
    int counter = 0; 

    // Get length of string. 
    for(int i = 0; i < strlen(user_name); i++){ 
     if(strncmp(&user_name[i], " ", 1) == 0){ 
      word_counter += 1; 
     } 
    } 
    word_counter += 1; 


    // Declare empty array and size. 
    char output[word_counter]; 

    // Iterate through array to assign first characters to new array. 
    for(int i = 0; i < strlen(user_name); i++){ 
     if(i == 0){ 
      output[counter] = toupper(user_name[i]); 
      counter += 1; 
     } 
     else if(strcmp(&user_name[i - 1], " ") == 0){ 
      output[counter] = toupper(user_name[i]); 
      counter += 1; 
     } 
    } 

    // Output result. 
    for(int i = 0; i < word_counter; i++){ 
     printf("%c\n", output[i]); 
    } 

    printf("\n"); 
} 

當輸出返回時,我只接收B。看起來輸出不是保存每個單詞的第一個字母。我是否宣佈輸出不正確?

+1

'strncmp(&user_name [i],「」,1)== 0'更簡單地寫成'username [i] =='''。 – Barmar

回答

2

strcmp(&user_name[i - 1], " ")不只是比較1個字符作爲inteneded(就像您的原始strncmp(&user_name[i], " ", 1)一樣)。

爲什麼不使用str [n] cmp(),爲什麼不只是if (name[i] == ' ') { ...

+0

我想比較最後一個字符。如果名字是'Barack Hussein Obama',我想問一下'H'和'O'前面的字符是否有空格。如果是這樣,我會知道這是這個詞的開頭。 – rebbailey

+2

@rebbailey這就是問題所在,'strcmp'意味着比較整個字符串,而你實際上只想比較一個字符。 –

相關問題