gpt4 book ai didi

c++ - 我想打印单词的缩写,但不知道我做错了什么

转载 作者:行者123 更新时间:2023-12-04 08:20:34 30 4
gpt4 key购买 nike

我想打印单词的缩写
编写一个 C 程序,该程序应将用户的组织名称作为字符串。您必须在该字符串上实现以下函数:
例如:
字 = 巴基斯坦国家石油
缩写:PSO
仅来自单词的大写字母
它仅打印 1 个字。
代码 :

#include <iostream>
using namespace std;

void printAbbrevation(char Word[], char WordAbb[]);
int findLength(char Word[])
{
int length = 0;

for (int i = 0; Word[i] != '\0'; i++)
{
length++;
}
return length;
}

void findAbbrevation(char Word[])
{
int WordLength = findLength(Word);
char WordAbb[] = {0};

for (int i = 0; i < WordLength; i++)
{
if (Word[i] >= 'A' && Word[i] <= 'Z')
{
WordAbb[i] = Word[i];
}
}
printAbbrevation(Word, WordAbb);
}

void printAbbrevation(char Word[], char WordAbb[])
{
int abbword = findLength(WordAbb);
cout << "Abbrevation of " << Word << " is = ";

for (int i = 0; i < abbword; i++)
{
cout << WordAbb[i];
}

}

int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.getline(Word,100);
cout << "Length of Word is = ";
cout << findLength(Word);
cout << endl;
findAbbrevation(Word);
return 0;
}
我得到的输出:
Output

最佳答案

您需要更改您的 findAbbrevation()像这样的功能:

void findAbbrevation(char Word[])
{
int WordLength = findLength(Word);
char WordAbb[25] = {0};
int j = 0;

int flag = 0;
for (int i = 0; i < WordLength; i++)
{
// To continue untill we get a space
// this marks the start of the new word
if(flag)
{
if(Word[i] == ' ')
{
flag = 0;
}
continue;
}
else
{
if (Word[i] >= 'A' && Word[i] <= 'Z')
{
WordAbb[j++] = Word[i];
flag = 1;
}
}
}
printAbbrevation(Word, WordAbb);
}
我所做的更改是:
  • 找到新单词时保留一个标志,这是通过检查字符串中的空格来完成的。
  • 对于找到的每个新单词,将它的第一个字符添加到缩写字符串中。
  • 为缩写字符串保留一个单独的计数器。
  • 关于c++ - 我想打印单词的缩写,但不知道我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65517035/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com