Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
2.5 kB
2
Indexable
Never
#define _CRT_SECURE_NO_WARNINGS
#define MAX_STRING_LEN 1000

#include <string>
#include <iostream>
#include <vector>

using namespace std;

char words[] = "Студенты, если у вас возникают вопросы, то можете смело задавать их прямо здесь";
vector <char*> words_arr;

void get_string(char* str) {
    int c, i = 0;
    while ((c = getchar()) != '\n' && c != EOF && i < MAX_STRING_LEN - 1) {
        str[i++] = c;
    }
    str[i] = '\0';
}

int find_last_word_len(char* words)
{
    _strrev(words);
    int len = 0;
    for (int i = 0; i < strlen(words); i++)
        if (words[i] == ' ' || words[i] == ',')
            break;
        else
            len++;
    _strrev(words);
    return len;
}

void reverse_word(char* word) {
    int len = strlen(word);
    for (int i = 0; i < len / 2; i++) {
        char temp = word[i];
        word[i] = word[len - i - 1];
        word[len - i - 1] = temp;
    }
}

void append_string(char* str1, char* str2) {
    size_t len1 = strlen(str1);
    size_t len2 = strlen(str2);
    str1[len1] = ' ';
    strncpy(str1 + len1 + 1, str2, len2 + 1);
}

int main()
{
    setlocale(LC_ALL, "Rus");
    cout << "Введите исходную строку: ";
    get_string(words);
    cout << "Исходная строка: " << words;


    int last_word_len = find_last_word_len(words);
    char* new_words = new char[MAX_STRING_LEN];
    new_words[0] = '\0';
    char* word = strtok(words, ", ");

    while (word != NULL)
    {
        int word_len = (word[strlen(word) - 1] == ',') ? strlen(word) - 1 : strlen(word);
        
        if (word_len > last_word_len)
        {
            reverse_word(word);
            new_words = strcat(new_words, word);
            new_words = strcat(new_words, " ");
        }
        else if (word_len < last_word_len)
        {
            words_arr.push_back(word);
        }
        else
        {
            new_words = strcat(new_words, word);
            new_words = strcat(new_words, " ");
        }
        word = strtok(NULL, " ,");
    }
    if (word != NULL) {
        append_string(new_words, word);
    }
    else {
        new_words[strlen(new_words) - 1] = '\0';
    }

    cout << "\nИзменённая строка: " << new_words;
    cout << "\nСлова, которые короче последнего слова: \n";
    for (char* every_word : words_arr)
    {
        cout << every_word << endl;
    }
    delete[] new_words;
}