我要求用戶輸入一個字符串。我想用大寫字母輸出每個單詞的第一個字母。不保存到數組的字符
實施例: 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
。看起來輸出不是保存每個單詞的第一個字母。我是否宣佈輸出不正確?
'strncmp(&user_name [i],「」,1)== 0'更簡單地寫成'username [i] =='''。 – Barmar