Найти в тексте самую короткую аббревиатуру, заменить все абревиатуры самой короткой.(СИ)

Нужна помощь начинающему програмисту!!! Ввести текст, состоящий из английских прописных, заглавных букв и цифр. Между словами могут быть один или несколько знаков препинания (. , ; : ! ? ... " " ( ) < > пробел), произвольный текст может начинаться с знаков препинания, букв или цифр. 1.Найти в тексте самую короткую аббревиатуру ( слово, которое содержит и ЦИФРЫ и БУКВЫ). 2. Заменить в тексте все аббревиатуры (только аббревиатуры), самой короткой. 3 . Вывести результат Прошу по возможности коментировать код : ) Заранее спасибо всем!

Пример:

Input text: ...Pasha!! 2020, anton. year; A1? b22222, Aleks123456789.

Result: ...Pasha!! 2020, anton. year; A1? A1, A1.


Ответы (1 шт):

Автор решения: Рамзес Жданов

Написал на коленке за часик, так что за возможные баги не ручаюсь, но результат выдает вроде бы правильный. Как и просили на чистом Си. Плюсы не использовал.

#include <string.h>
#include <windows.h>
#include <stdio.h>
typedef int bool;

//Метод получения наиболее короткой аббревиатуры
void getShortestAbbreviation(IN const char*, IN unsigned int, OUT char *, IN unsigned int);

//Метод проверки является ли токен подходящим
bool IsTokenApplicable(IN const char*, IN unsigned int);

//Метод получения очищенной строчки от лишних символов
void getPurifiedStringFromUnnecessaryLetters(IN const char*, IN unsigned int, OUT char*, OUT unsigned int, IN bool);

//Метод, позволяющий понять, какие у токена имеются символы в самом конце, которые в обычной ситуации игнорировались
void getUnnecessarySymbolsAtTheEndOfTheToken(IN const char*, IN unsigned int, OUT char*, IN unsigned int);

//Замена одного токена на другой
void replaceTokenWithAnother(IN const char* strInput, IN unsigned int uiLength, IN const char* strPattern, IN unsigned int uiPatternLength, OUT char* strOutModifiedString, IN unsigned int uiLengthOfModifiedString);

//Метод, который в выходном OUT-параметре возвращает нашу целевую строчку
void getModifiedString(IN const char* strInput, IN unsigned int uiLength, IN const char* strPattern, IN unsigned int uiPatternLength, OUT char* strOutModifiedString, IN unsigned int uiLengthOfModifiedString);


int main()
{
    char strInput[] = { "Pasha!! 2020, anton. year; A1? b22222, Aleks123456789." };

    char strShortestAbbreviation[255] = { 0 };
    getShortestAbbreviation(strInput, sizeof(strInput), strShortestAbbreviation, sizeof(strShortestAbbreviation));
    if (strShortestAbbreviation[0] == NULL)
    {
        printf("ERROR: strShortestAbbreviation is NULL. Line: %d; File: %s", __LINE__, __FILE__);
        return -1;
    }

    char strModifiedString[255] = { 0 };
    getModifiedString(strInput, sizeof(strInput), strShortestAbbreviation, strlen(strShortestAbbreviation), strModifiedString, sizeof(strModifiedString));
    if (strModifiedString[0] == NULL)
    {
        printf("ERROR: strModifiedString is NULL. Line: %d; File: %s", __LINE__, __FILE__);
        return -1;
    }

    printf("INPUT: %s\nOUTPUT: %s\n", strInput, strModifiedString);


    return 0;
}


void getPurifiedStringFromUnnecessaryLetters(
    IN const char* strInput, 
    IN unsigned int uiLength, 
    OUT char* strOutputString, 
    OUT unsigned int uiOutputStringLength,
    IN bool flgCheckSpace)
{
    char strTmpBuff1[255] = { 0 };
    unsigned int uiLocalIndex = 0;
    for (unsigned int i = 0; i < uiLength; i++) //Уберем лишние символы из строки (. , ; : ! ? ... " " ( ) < >), кроме пробелов
    {
        if ((strInput[i] >= 'a' && strInput[i] <= 'z') || (strInput[i] >= 'A' && strInput[i] <= 'Z') ||
            (strInput[i] >= '0' && strInput[i] <= '9') ||
            (strInput[i] == '\0') || (flgCheckSpace == TRUE && strInput[i] == ' '))
        {
            strTmpBuff1[uiLocalIndex] = strInput[i];
            uiLocalIndex++;
        }
    }

    strcpy_s(strOutputString, uiOutputStringLength, strTmpBuff1);
}

void getShortestAbbreviation(IN const char* strInput, IN unsigned int uiLength, OUT char *strResult, IN unsigned int uiResultLength)
{
    char strTmpBuff1[255] = { 0 };
    char strTmpBuff2[255] = { 0 };

    if (strInput != NULL && uiLength > 0) //Проверим, что указатель не нулевой и длина массива больше нуля, т.е. он не пустой
    {

        //Получим очищенную аббревиатуру без лишних знаков
        getPurifiedStringFromUnnecessaryLetters(strInput, uiLength, strTmpBuff1, sizeof(strTmpBuff1), TRUE);

        //Получим же токены из получившейся строчки
        char *strLocalResult = NULL;
        char *strNext_token = NULL;
        strcpy_s(strTmpBuff2, sizeof(strTmpBuff2), strTmpBuff1);

        char* token = strtok_s(strTmpBuff2, " ", &strNext_token);

        bool flgIsApplicable = FALSE;
        while (token != NULL)
        {
            flgIsApplicable = IsTokenApplicable(token, sizeof(token));
            if (flgIsApplicable == TRUE)
            {
                if (strLocalResult == NULL || (strLocalResult != NULL && sizeof(strLocalResult) < sizeof(token)))
                {
                    strLocalResult = token;
                }
            }
            token = strtok_s(NULL, " ", &strNext_token);
        }
        strcpy_s(strResult, uiResultLength, strLocalResult);
    }
}

bool IsTokenApplicable(IN const char* strInput, IN unsigned int uiLength)
{
    bool flgIsFoundLetters = FALSE;
    bool flgIsFoundFigures = FALSE;

    for (unsigned int i = 0; i < uiLength; i++)
    {
        if ((strInput[i] >= 'a' && strInput[i] <= 'z') || (strInput[i] >= 'A' && strInput[i] <= 'Z'))
        {
            flgIsFoundLetters = TRUE;
        }
        if ((strInput[i] >= '0' && strInput[i] <= '9'))
        {
            flgIsFoundFigures = TRUE;
        }
        if (flgIsFoundLetters == TRUE && flgIsFoundFigures == TRUE)
        {
            return TRUE;
        }
    }
    return FALSE;
}


void getUnnecessarySymbolsAtTheEndOfTheToken(IN const char* strInput, IN unsigned int uiLength, OUT char* strOutModifiedString, IN unsigned int uiLengthOfModifiedString)
{
    char strTmpBuff1[255] = { 0 };

    unsigned int uiLocalIndex = 0;
    for (unsigned int i = 0; i < uiLength; i++)
    {
        if (!((strInput[i] >= 'a' && strInput[i] <= 'z') || (strInput[i] >= 'A' && strInput[i] <= 'Z') || (strInput[i] >= '0' && strInput[i] <= '9')))
        {
            strTmpBuff1[uiLocalIndex] = strInput[i];
            uiLocalIndex++;
        }
    }

    strcpy_s(strOutModifiedString, uiLengthOfModifiedString, strTmpBuff1);
}


void replaceTokenWithAnother(IN const char* strInput, IN unsigned int uiLength, IN const char* strPattern, IN unsigned int uiPatternLength, OUT char* strOutModifiedString, IN unsigned int uiLengthOfModifiedString)
{
    char strTmpBuff1[255] = { 0 };
    char strTmpBuff2[255] = { 0 };
    char strTmpBuffResult[255] = { 0 };
    strcpy_s(strTmpBuff1, sizeof(strTmpBuff1), strPattern);
    getUnnecessarySymbolsAtTheEndOfTheToken(strInput, uiLength, strTmpBuff2, sizeof(strTmpBuff2));

    sprintf_s(strTmpBuffResult, sizeof(strTmpBuffResult), "%s%s", strTmpBuff1, strTmpBuff2);

    strcpy_s(strOutModifiedString, uiLengthOfModifiedString, strTmpBuffResult);
}


void getModifiedString(IN const char* strInput, IN unsigned int uiLength, IN const char* strPattern, IN unsigned int uiPatternLength, OUT char* strOutModifiedString, IN unsigned int uiLengthOfModifiedString)
{
    char strOutputModifiedToken[255] = { 0 };

    char strCopyOfInputString[255] = { 0 };

    if (strInput != NULL && uiLength > 0 && strPattern != NULL && uiPatternLength > 0)
    {
        char *strNext_token = NULL;
        strcpy_s(strCopyOfInputString, sizeof(strCopyOfInputString), strInput);
        char* token = strtok_s(strCopyOfInputString, " ", &strNext_token);


        int iIndex = 0;
        char strTmpBuff2[255] = { 0 };
        char strLocalToken[255] = { 0 };
        while (token != NULL)
        {
            if (IsTokenApplicable(token, strlen(token)) == TRUE)
            {
                strcpy_s(strLocalToken, sizeof(strLocalToken), token);
                replaceTokenWithAnother(strLocalToken, strlen(strLocalToken), strPattern, strlen(strPattern), strTmpBuff2, sizeof(strTmpBuff2));
            }

            if (strOutputModifiedToken[0] != NULL)
            {
                strOutputModifiedToken[iIndex] = ' ';
                iIndex++;
            }

            if (strTmpBuff2[0] == NULL)
            {
                for (int i = 0; i < strlen(token); i++)
                {
                    strOutputModifiedToken[iIndex] = token[i];
                    iIndex++;
                }
            }
            else
            {
                for (int i = 0; i < strlen(strTmpBuff2); i++)
                {
                    strOutputModifiedToken[iIndex] = strTmpBuff2[i];
                    iIndex++;
                }
            }


            token = strtok_s(NULL, " ", &strNext_token);
        }


        strcpy_s(strOutModifiedString, uiLengthOfModifiedString, strOutputModifiedToken);
    }
}

введите сюда описание изображения

→ Ссылка