我想打印单词的缩写
编写一个 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;
}
最佳答案
您需要像这样更改您的 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/