簡體   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