Cannot properly eliminate string one from another character by character
在这里,函数(sub)将两个字符串作为输入,遍历两个字符串,我试图找出string1与string2相比是否有任何匹配项。如果有的话,将string1的那个字符替换为NULL字符。现在,此方法适用于非重复字符。但是,如果string1具有多个匹配一次的字符,则全部替换为NULL字符,而我只需要替换一次即可。例如,如果string1和string2为122和2,则消除后我需要1 2,其中我现在得到一个1。
1 2 3 4 5 6 7 8 9 | void sub (string str1, string str2){ int i,j,k; for(i=0; i<=str2.size() ; i++){ for(j=0; j<=str1.size() ; j++ ){ if( str2[i] == str1[j] ) str1[j] = NULL; } } cout<<str1; |
如果str1 = 122和str2 = 2
,则预期结果是1 2而不是1
您正在使事情变得更加困难。
成员函数std :: basic_string :: find_first_of将定位
std :: basic_string :: erase函数可以删除
您的
1 2 3 4 | void sub (std::string& s1, const std::string& s2) { s1.erase (s1.find_first_of (s2)); } |
使用给定字符串的简短示例为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <string> void sub (std::string& s1, const std::string& s2) { s1.erase (s1.find_first_of (s2)); } int main (void) { std::string s1 ("122"), s2 ("2"); sub (s1, s2); std::cout <<"s1:" << s1 <<"\ s2:" << s2 << '\ '; } |
使用/输出示例
1 2 3 | $ ./bin/sub1at2 s1: 1 s2: 2 |
仔细检查一下,如果还有其他问题,请通知我。
不能通过将其设置为
首先遍历第二个字符串,然后使用哈希表将
1 2 3 4 5 6 7 8 9 10 | string remove_first_duplicates(string s1, string s2) { unordered_map<char, bool> m; string result; for (char i : s2) m[i] = true; for (char i : s1) { if (!m[i]) result += i; m[i] = false; } return result; } |
将字符归零并不能阻止它们成为字符串的一部分。为此,您必须移动其余的并调整长度。
如果只想执行一次,则在第一个匹配项上,然后使用
请考虑将其分为两个功能:一个用于查找匹配项,一个调用该函数并使用结果删除第一个匹配项。
据我所知,您想从str1中删除一个与str2中的匹配项相对应的字符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | void sub(string str1, string str2) { int i = 0, j = 0; while (j < str2.size()) { if (str1[i] == str2[j]) { str1[i] = NULL; // could use str1.erase(i,1) i = 0; j += 1; continue; } else i += 1; if (i == str1.size() - 1) { i = 0; j += 1; } } cout<<str1<<endl; } |
这将产生您想要的输出。但这会在str1中产生NULL char,更好的选择是使用