Как сделать пропуск лишних пробелов для введенного текста? Получилось написать для заданного.
#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();
}
Примерно так:
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
Как ни странно, но это также можно сделать с помощью стандартной библиотеки, используя функцию 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';
}
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости