#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void rmvdupli(string s)
{
if (s.length() == 1)
{
cout << s;
return;
}
char c = s.at(0);
if (((s.substr(1)).find(c)) >= 0)
cout << "";
else
cout << c;
rmvdupli(s.substr(1));
}
int main()
{
cout << "Enter the string " << endl;
string s;
cin >> s;
rmvdupli(s);
return 0;
}
輸出
輸入字串
abcdc
C
代碼有什么問題?看起來完全沒問題,但沒有答案!!
uj5u.com熱心網友回復:
我通過一些重構修改了您的代碼,以修復錯誤并提高其可讀性和性能。我還添加了另一個多載函式,該函式明顯更快并使用 0 堆分配。雖然它做同樣的事情,但以一種更優化的方式。
這里:
#include <iostream>
#include <string>
#include <string_view>
// this is basically your function but is more efficient now
void removeDuplicateChars( const std::string& str )
{
if ( str.length( ) == 1 )
{
std::cout << str;
return;
}
const char firstChar = str[ 0 ];
const std::string&& restOfStr { str.substr( 1 ) };
if ( restOfStr.find( firstChar ) == std::string::npos )
{
std::cout << firstChar;
}
else
{
std::cout << "";
}
removeDuplicateChars( restOfStr );
}
// this one is far superior to the above one
void removeDuplicateChars( std::string_view&& strView )
{
if ( strView.length( ) == 1 )
{
std::cout << strView;
return;
}
const char firstChar = strView[ 0 ];
strView.remove_prefix( 1 );
if ( strView.find( firstChar ) == std::string_view::npos )
{
std::cout << firstChar;
}
else
{
std::cout << "";
}
removeDuplicateChars( std::move( strView ) );
}
int main( )
{
std::cout << "Enter the string: ";
std::string str;
std::cin >> str;
removeDuplicateChars( str ); // this calls the first overload
std::cout << '\n';
removeDuplicateChars( std::string_view( "ababcdc" ) ); // this calls the
// second overload
return 0;
}
示例輸入/輸出:
Enter the string: ababcdc
abdc
abdc
我強烈建議您放棄第一個過載而只使用第二個。不僅它的速度更快,而且支持的型別std::string,std::string_view和C風格的字串。
這里有一些有用的鏈接來提高你的知識:
std::string_view
std::string::substr
std::string::find
uj5u.com熱心網友回復:
下面一行:
if (((s.substr(1)).find(c)) >= 0)
應改為:
if (s.substr(1).find(c) != std::string::npos)
它基本上意味著c在s.substr(1).
std::string::npos如果未找到該字符,則find回傳。
uj5u.com熱心網友回復:
我試圖解決你的這個問題。
我所做的是,我用空格替換了重復的字符。
如果您想洗掉空格,您可以在互聯網上輕松找到代碼。
C 代碼:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void RemoveDuplicateChar(string inputString)
{
if(inputString.length() == 1){
cout << inputString;
cout << "\nIt has only one character";
}else{
int stringLength = inputString.length();
cout<< "Original string: ";
cout << inputString;
cout << "\n";
for(int i =0 ; i<stringLength; i ){
for(int j = i 1; j< stringLength; j ){
if(inputString[i] == inputString[j]){
inputString[j] = ' ';
}else{
continue;
}
}
}
cout << "Duplicate character removed\n";
cout << "New String: ";
cout << inputString;
}
}
int main()
{
string input;
cout << "Enter a string with repeated characters: ";
cin >> input;
RemoveDuplicateChar(input);
return 0;
}
輸出:
輸入包含重復字符的字串:ababcdc
原始字串:ababcdc
洗掉了重復字符
新字串:ab cd
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398745.html
