I need your help with a program in Turbo C++.
I need to create a program using a string. Write any sentence, and in the sentence I need to find the first b or B letter then write cb before it.
For example:
acdcb -> acdccbb
I tried to do it, but can do it only like a replace. I just started to learn strings, so I have such code:
#include <iostream.h>
#include <conio.h>
#include <string.h>
int main()
{
clrscr();
const int N=100;
char m[N];
char r[]="cb";
int p=0,kb=0;
cout<<"Sentence: ";
cin>>m;
p=strlen(m);
cout<<"String length = "<<p<<"\n";
for(int i=0;i<p;i++)
{
if(m[i]=='b'||m[i]=='B')
{
kb++;
if(kb==1)
{
m[i-1]='b';
m[i-2]='c';
}
}
}
cout<<"New Sentence : "<<m;
p=strlen(m);
cout<<"\ncount of letters = "<<p;
getch();
}

You are only replacing existing characters, you are not shifting any characters around to make room for the new characters.
So, for example, if you enter
dasdasB,mwill look like this:What you are doing is simply replacing the 2nd
awithc, and the 2ndswithb:Instead, you need to shift all of the characters including and after
Bto the right 2 spaces:And then you can fill in the empty spaces you just created:
I'll leave that as an exercise for you to figure out how to do that shifting.
That being said, this code would be a lot easier if you were using
std::stringinstead of achar[]array, asstd::stringhasfind_first_of()andinsert()methods, eg:Online Demo