问题描述
我得到的提示是:首字母缩写词是由一组短语中单词的首字母组成的单词。编写一个程序,其输入是一个短语,其输出是输入的首字母缩写词。如果单词以小写字母开头,请不要在首字母缩略词中包含该字母。假设输入中至少有一个大写字母。
另外,我得到了以下函数的使用:void CreateAcronym(char userPhrase[],char userAcronym[]).
我的代码问题是只有第一个字母被保存到 userAcronym 变量中。 例如,当字符串是 Institute of Electrical and Electronics Engineers 时。我得到的输出只是 I。我需要改变什么才能得到剩余的字母?
感谢您的帮助。
到目前为止我的代码是:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 60
void CreateAcronym(char userPhrase[],char userAcronym[]){
int i;
int j=0;
for(i = 0; i < strlen(userPhrase); ++i){
if(isupper(userPhrase[i])){
userAcronym[j]=userPhrase[i];
}
j++;
}
printf("%s",userAcronym);
}
int main(void) {
char phrase[MAX];
char acronym[10];
fgets(phrase,MAX,stdin);
CreateAcronym(phrase,acronym);
return 0;
}
解决方法
对于初学者来说,函数 CreateAcronym
应该至少像这样声明
void CreateAcronym( const char userPhrase[],char userAcronym[]);
因为传递的包含短语的字符串不会在函数内更改。
但是像这样声明函数会更好
char * CreateAcronym( const char userPhrase[],char userAcronym[]);
该函数不应输出任何内容。由函数的调用者决定是否输出函数内部形成的首字母缩略词。
该函数调用未定义的行为,因为数组首字母缩写词没有得到字符串。
此外,for 循环中还有一个错误
for(i = 0; i < strlen(userPhrase); ++i){
if(isupper(userPhrase[i])){
userAcronym[j]=userPhrase[i];
}
j++;
}
其中变量 j
在循环的每次迭代中递增。
并且在循环条件下调用函数strlen
效率低下。
此外,该函数不会仅将单词的首字母大写字母复制到目标数组。它试图复制任何大写字母。所以 for 循环在任何情况下都没有意义。
可以通过以下方式定义函数,如下面的演示程序所示。
#include <stdio.h>
#include <ctype.h>
char * CreateAcronym( const char userPhrase[],char userAcronym[] )
{
char *p = userAcronym;
while ( *userPhrase )
{
while ( isspace( ( unsigned char )*userPhrase ) ) ++userPhrase;
if ( isupper( ( unsigned char )*userPhrase ) ) *p++ = *userPhrase;
while ( *userPhrase && !isspace( ( unsigned char )*userPhrase ) ) ++userPhrase;
}
*p = '\0';
return userAcronym;
}
int main(void)
{
const char *phrase = "Institute of Electrical and Electronics Engineers";
char acronym[10];
puts( CreateAcronym( phrase,acronym ) );
return 0;
}
程序输出为
IEEE
,
试试吧。首先,您在“if”中使用了 j++。其次,您没有将 '\0' 放在 userAcronym 字符串中。 '\0' 表示你的字符串到这里结束,所有的字符串都将打印在这个符号之前。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 60
void CreateAcronym(char userPhrase[],char userAcronym[]){
int i;
int j = 0;
for(i = 0; i < strlen(userPhrase); i++){
if(isupper(userPhrase[i])){
userAcronym[j] = userPhrase[i];
j++;
}
}
userAcronym[j] = '\0';
printf("%s",userAcronym);
}
int main(){
char phrase[MAX];
char acronym[10];
fgets(phrase,MAX,stdin);
CreateAcronym(phrase,acronym);
return 0;
}