Другие языки программирования и технологии
замена слов в строках С++
Такая задача: нужно из сформированной строки (состоящей из латинских символов) заменить все вхождения с "lat" на "tal". при этом указать количество вхождений. инициализацию строки организовать вручную. как подсчитать количество "lat" в строке я в принципе понял. а вот как заменить и выдать на экран изменненый вариант строке не пойму. помогите. вот так я нахожу кол-во вхождений: #include<conio.h> #include<iostream.h> #include<stdio.h> #include<string.h> #include<ctype.h> int main(){ const int len=61; char word[len],line[len]; cout<<"vvedite stroky ne bolshe 60 simvolov"; cin.getline(line, len); cout<<"vvedite frazu poiska"; cin>>word; int l_word=strlen(word); int count=0; char*p=line; while(p=strstr(p,word)){ char*c=p; p+=l_word; if(c!=line) if(!ispunct(*(c-1))&&!isspace(*(c-1))) continue; if(ispunct(*p)||isspace(*p)||(*p=='\0')) count++;} cout<
Сергей Украинский, стандартной библиотекой не то, что можно, а нужно пользоваться. Однако ваш код не будет работать, если длины строки-образца и строки-подстановки не совпадают. Самое простое решение в этом случае - заменять вхождения, двигаясь справа налево, используя стек для хранения позиций вхождения строки-образца. Но это же и самое неэффективное решение, поскольку порождает 100500 операций выделения-копирования-освобождения памяти. Кроме того, если строка-подстановка короче образца, то тоже работать не будет. Более эффективное решение - формировать строку последовательно, двигаясь слева направо, используя потоки.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void main()
{
string source;
cout << "Enter source string: ";
getline(cin, source);
const string pattern = "lat";
const string substitution = "salo";
const int pattern_length = pattern.length();
ostringstream result;
int previous = 0;
int matches_count = 0;
for (
int position = source.find(pattern);
position != string::npos;
position = source.find(pattern, position + 1)
)
{
if (previous != position)
result << source.substr(previous, position - previous);
result << substitution;
previous = position + pattern_length;
matches_count++;
}
const int source_length = source.length();
if (previous < source_length)
result << source.substr(previous, source_length - previous);
cout << "Matches with \"" << pattern << "\" found: " << matches_count << endl;
cout << "Modified string is: " << result.str() << endl;
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void main()
{
string source;
cout << "Enter source string: ";
getline(cin, source);
const string pattern = "lat";
const string substitution = "salo";
const int pattern_length = pattern.length();
ostringstream result;
int previous = 0;
int matches_count = 0;
for (
int position = source.find(pattern);
position != string::npos;
position = source.find(pattern, position + 1)
)
{
if (previous != position)
result << source.substr(previous, position - previous);
result << substitution;
previous = position + pattern_length;
matches_count++;
}
const int source_length = source.length();
if (previous < source_length)
result << source.substr(previous, source_length - previous);
cout << "Matches with \"" << pattern << "\" found: " << matches_count << endl;
cout << "Modified string is: " << result.str() << endl;
}
Если C++, то можно используя стандартную библиотеку STL:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
cin>>s;
unsigned int c = 0;
while (s.find("lat")!=string::npos)
{
s.replace(s.find("lat"), 3, "tal");
c++;
}
cout<
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
cin>>s;
unsigned int c = 0;
while (s.find("lat")!=string::npos)
{
s.replace(s.find("lat"), 3, "tal");
c++;
}
cout<
Похожие вопросы
- замена слов в строке в СИ
- FASM. Замена символов в строке, используя подпрограммы.
- C# Парсинг слов из строки без регистра
- Програма на С++ Ввести с клавиатуры строку символов и перевернуть каждое четное слово в строке.
- C++. Поменять местами слова в строке
- Как заменить слово в строке?Паскаль
- Как разделить слова в строке, чтобы их потом сравнивать друг с другом и сортировать? (Паскаль)
- Как найти слово в строке. Паскаль
- найти первую букву второго слова в строке. c++
- как подсчитать количество слов в строке разделённым больше чем одним пробелом(Delphi)