字符串程序(替换字母)
我需要你关于 Turbo C++ 程序的帮助。
我需要使用字符串创建一个程序。写任何句子,在句子中我需要找到第一个 b
或 B
字母,然后在它前面写上 cb
。
例如:
acdcb
-> acdccbb
我尝试这样做,但只能像替换一样做到。我刚刚开始学习字符串,所以我有这样的代码:
#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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只是替换现有角色,而不是移动任何角色来为新角色腾出空间。
因此,例如,如果您输入
dasdasB
,m
将如下所示:您所做的只是替换第二个
a
与c
,第二个s
与b
:相反,您需要转移所有右侧包括
B
在内的字符2 个空格:然后您可以填写刚刚创建的空白区域:
我将把它作为练习,让您弄清楚如何进行这种转换。
话虽这么说,如果您使用
std::string
而不是char[]
数组,这段代码会容易得多,如std::string< /code> 有
find_first_of()
和insert()
方法,例如:在线演示
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
,m
will look like this:What you are doing is simply replacing the 2nd
a
withc
, and the 2nds
withb
:Instead, you need to shift all of the characters including and after
B
to 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::string
instead of achar[]
array, asstd::string
hasfind_first_of()
andinsert()
methods, eg:Online Demo
您需要创建一个大小为 3 且大于 m 的新数组。 c 和 b 将占用 2 个字符,最后一个字符为“\0”,表示 char 数组的结尾。我有一个代码,可以对您有所帮助。它在 b 字符之前添加了 c 和 b 两个字符。
You need to create a new array with size 3 greater than m. 2 characters will be occupied by c and b and last one would be '\0' indicating the end of char array. I have a code which can be helpful for you. It adds two more characters of c and b before the b character.