6

Как сделать пропуск лишних пробелов для введенного текста? Получилось написать для заданного.

 #include <iostream>
using namespace std;
#include  <conio.h>
#include <stdio.h>

void main()
{
    setlocale(0, "rus");
    char nach1[] = "Its me      Dio ";
    char con1[50];
    int jj = 0;


    for (int i = 0; i < strlen(nach1 - 1); i++)
    {
        if (nach1[i] == ' ' && nach1[i + 1] == ' ')continue;
        con1[jj] = nach1[i], jj++;
    }

    con1[jj] = 0;

    char* vr = con1;
    if (con1[0] == ' ')vr++;

    cout << vr << endl << endl;
    _getch();
}

2 ответа 2

3

Примерно так:

void removeSpaces(std::string& str)
{
    for (std::string::iterator it = str.begin(); it != str.end(); it++)
    {   
        std::string::iterator begin = it;
        while (it != str.end() && ::isspace(*it) )it++;
        if (it - begin > 1)
            it = str.erase(begin + 1, it) - 1;
    }
}

Вход: str sdfg f

Выход: str sdfg f

2

Как ни странно, но это также можно сделать с помощью стандартной библиотеки, используя функцию std::unique_copy/4.

Пример:

#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>

void remove_spaces(std::string& str)
{
    str.erase(
        std::unique_copy(str.begin(), str.end(), str.begin(),
                     [](char c1, char c2){ return c1 == ' ' && c2 == ' '; }),
        str.end());
}

int main()
{
    std::string s1 = "The      string    with many       spaces!";
    std::cout << "before: " << s1 << '\n';
    remove_spaces(s1);
    std::cout << "after:  " << s1 << '\n';
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.