c-我正在做一项任务,要求我制作一个函数,从字符串中创建首字母缩写,然后返回首字母缩写



我得到的提示是:首字母缩略词是由短语中单词的首字母组成的单词。编写一个程序,其输入是一个短语,其输出是输入的首字母缩写。如果一个单词以小写字母开头,不要将该字母包含在首字母缩略词中。假设输入中至少有一个大写字母。

此外,我还得到了以下函数:void CreateAcronym(char userPhrase[],char userAcronym[](。

我对代码的问题是,只有第一个字母被保存到userAcronym变量中。例如,当字符串为电气和电子工程师协会时。我得到的输出只有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++;

}

其中变量CCD_ 2在循环的每次迭代中递增。

并且在循环的情况下调用函数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 = '';

return userAcronym;
}
int main(void) 
{
const char *phrase = "Institute of Electrical and Electronics Engineers";
char acronym[10];

puts( CreateAcronym( phrase, acronym ) );

return 0;
}

程序输出为

IEEE

试试看。首先,您在"如果";。其次,您没有在userAcronym字符串中放入"\0"\"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] = '';
printf("%s", userAcronym);
}
int main(){
char phrase[MAX];
char acronym[10];
fgets(phrase, MAX, stdin);
CreateAcronym(phrase, acronym);
return 0;
}

最新更新