繁体   English   中英

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

[英]To compare two strings and remove the same characters from string 1 and print the string 2 using C++

我是一个编程新手,我不得不使用 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 中的任何字符都不匹配,则 append 将此字符转换为新字符串,否则继续不附加。 对 string2 中的所有字符继续此操作。 现在将新字符串分配为 string1。 这使用了额外的 o(n) 空间,但更简单。

我建议使用c_str将您的字符串表示为字符数组(或者甚至更好地以字符数组而不是字符串数据类型开头)。 完成此操作后,通过每个数组编写 function 到 go 并比较字符(在需要时删除),它的效率有点低,但它会完成这项工作而且很简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM