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

标签 c++ arrays

我想打印单词的缩写 编写一个 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/

相关文章:

java - 如何向数组添加新元素?

c++ - 我可以使用 "using"而不是 "typedef"作为指向类成员变量的指针吗?

c++ - Boost ASIO - 如何编写控制台服务器 2

c++ - 在C++中使用kinect拾取2个手势

c++ - 如何在 C++ 中搜索字符串数组

arrays - 如何从 &str 转换为 [i8; 256]

c++ - 在 C++ OpenMP 中为每个线程定义一个优先级队列

C++ 读取前一个函数堆栈帧

arrays - 如何从 Typescript 中的数组获取不同的值

java - int[] table = new int[10],x;是有效语法吗?