gpt4 book ai didi

c++ - 比较两个字符串并从字符串 1 中删除相同的字符并使用 C++ 打印字符串 2

转载 作者:太空宇宙 更新时间:2023-11-04 12:18:14 42 4
gpt4 key购买 nike

我是编程新手,一直卡在必须使用 C++ 比较两个字符串的地步:字符串 1 和字符串 2 的相同字符,然后从字符串 1 中删除这些字符并打印字符串 2。期待您的帮助。我的代码是这样的:

#include<string>
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
string first_string;
string second_string;
string::size_type start_position=0;

cout<<"Please enter the first string: "<<endl;
getline(cin,first_string);

cout<<"Please enter the Second string: "<<endl;
getline(cin, second_string);

while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
second_string.replace( start_position, first_string.size(), "" );
start_position++;
}
}
cout<<"The Result is as follws: "<<second_string<<endl;
getch();
return 0;

}

期待您的帮助。

问候,山姆

最佳答案

将 string2 中的每个字符与 string1 中的所有字符进行比较。如果 string2 中的字符与 string1 中的任何字符都不匹配,则将此字符附加到新字符串,否则继续不附加。对 string2 中的所有字符继续此操作。现在将新字符串指定为 string1。这使用额外的 o(n) 空间但更简单。

关于c++ - 比较两个字符串并从字符串 1 中删除相同的字符并使用 C++ 打印字符串 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6530008/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com