调整大小() 用于更改字符数。下面我们将描述在C++中由STD::String::Rsisie()支持的两个语法 返回值: 没有一个
null
语法1: 将*的字符数调整为num。
void string ::resize (size_type num) num: New string length, expressed in number of characters. Errors: Throws length_error if num is equal to string ::npos. Throws length_error if the resulting size exceeds the maximum number of characters(max_size()).
注: 如果num>size(),则其余字符由“”初始化。
// CPP code for resize (size_type num) #include <iostream> #include <string> using namespace std; // Function to demonstrate insert void resizeDemo(string str) { // Resizes str to a string with // 5 initial characters only str.resize(5); cout << "Using resize : " ; cout << str; } // Driver code int main() { string str( "GeeksforGeeks " ); cout << "Original String : " << str << endl; resizeDemo(str); return 0; } |
输出:
Original String : GeeksforGeeks Using resize : Geeks
语法2: 使用字符填充size()和num之间的差异。
void string ::resize (size_type num, char c ) num: is the new string length, expressed in number of characters. c: is the character needed to fill the new character space. If num > size() : character c is used to fill space. If num < size() : String is simply resized to num number of characters. Errors: Throws length_error if num is equal to string ::npos. Throws length_error if the resulting size exceeds the maximum number of characters(max_size()).
// CPP code for resize (size_type num, char c ) #include <iostream> #include <string> using namespace std; // Function to demonstrate insert void resizeDemo(string str) { cout << "Using resize :" << endl; cout << "If num > size() : " ; // Resizes str to character length of // 15 and fill the space with '$' str.resize(15, '$' ); cout << str << endl; cout << "If num < size() : " ; // Resizes str to a string with // 5 initial characters only str.resize(5, '$' ); cout << str; } // Driver code int main() { string str( "GeeksforGeeks" ); cout << "Original String : " << str << endl; resizeDemo(str); return 0; } |
输出:
Original String : GeeksforGeeks Using resize : If num > size() : GeeksforGeeks$$ If num < size() : Geeks
本文由 萨希·提瓦里 .如果你喜欢极客(我们知道你喜欢!)如果你想投稿,你也可以用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END