我正在做一個需要反轉字串元素的練習,例如 HelloWorld - dlroWolleH
我的原始代碼如下:
std::string reverseString(std::string text)
{
std::string new_string = "";
int index = 0;
int pos_text = text.size();
while (index <= text.size()) {
new_string[index] = text[pos_text]; //Line doesn't work.
pos_text--;
index ;
}
return new_string;
}
但是,在網上查看,while回圈內的代碼塊是這樣的。
new_string = new_string text[pos_text];
有人可以向我解釋為什么它需要像上面的那行嗎?我的印象是字串是一個字符陣列?
uj5u.com熱心網友回復:
您宣告了一個空字串
std::string new_string = "";
你可以等效地寫
std::string new_string;
所以你不能使用空字串的下標運算子來改變它的內容
new_string[index] = text[pos_text];
同樣在賦值的右運算元中也使用了無效的索引運算式pos_text。你必須使用運算式pos_text - 1。否則,字符 '\0' 將被寫入新字串的第一個位置。
相反,你可以寫
new_string = text[pos_text - 1];
或(同樣)
new_string.push_back( text[pos_text - 1] );
至于這個說法
new_string = new_string text[pos_text];
那又必須寫成
new_string = new_string text[pos_text - 1];
然后對于 std::string 類,定義了多載運算子 與 ty[e 的右運算元char。
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator (const basic_string<charT, traits, Allocator>& lhs, charT rhs);
注意while回圈的條件
while (index <= text.size())
是不正確的。你必須寫
while (index < text.size())
定義函式的最簡單方法如下
std::string reverseString( const std::string &text )
{
return { text.rbegin(), text.rend() };
}
如果像你一樣使用回圈,那么函式可以定義為
std::string reverseString( const std::string &text )
{
std::string new_string;
new_string.reserve( text.size() );
for ( auto i = text.size(); i != 0; )
{
new_string = text[--i];
}
return new_string;
}
uj5u.com熱心網友回復:
有人可以向我解釋為什么它需要像上面的那行嗎?我的印象是字串是一個字符陣列?
實際上,字串是大小不固定的動態陣列。它們使 運算子多載,因此您可以使用 . 附加兩個字串str1 = str2。例如,"hello" "world" == "helloworld"
當您創建時new_string,您會創建一個空字串,因此您無法訪問它的任何元素,因為它沒有。這就是為什么你需要使用 =, 來附加一個元素。
注意:在實踐中,您應該使用std::reverse(string.begin(), string.end())自定義演算法而不是自定義演算法。見這里:https ://en.cppreference.com/w/cpp/algorithm/reverse
uj5u.com熱心網友回復:
當您在字串中使用 符號時,它會將字符附加到該字串的末尾。我們在編程中稱其為“運算子多載”。
例子:
string word1 = "Hello";
string word2 = "World";
word1 = word1 word2;
這里word1變成了HelloWorld。word1 = word1 word2輸入這行代碼有不同的方法,在網上看你可以看到它word1 = word2,這也有效并且給你相同的結果。
這也是一個反轉單詞的解決方案:
string reverseString(string word)
{
int size = word.length();
string revWord;
for(int i = 0; i < size; i )
{
revWord = word[size-i-1];
}
return revWord;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452330.html
