描述
给定一个字符串,逐个翻转字符串中的每个单词。
说明
单词的构成:无空格字母构成一个单词
样例
给出s = “the sky is blue”,返回"blue is sky the"
void reverse_str(string&s)
{
int n = s.size();
int left = 0;
int right = n - 1;
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
int found = s.find_first_of(" ");
int curr = 0;
bool tag = true;
while (tag)
{
if (found == string::npos)
{
tag = false;
found = s.size();
}
int head = curr;
int tail = found - 1;
while (head < tail)
{
swap(s[head], s[tail]);
head++;
tail--;
}
curr = found+1;
found = s.find_first_of(" ",found+1);
}
}
int main()
{
string s = "i love you";
reverse_str(s);
for (auto& x : s)
{
cout << x;
}
cout << endl;
return 0;
}
总结:
几个很有意思的函数
1.first_of_all()(括号里是查找的值,返回匹配值的下标)
具体查看:https://blog.csdn.net/qq_40968179/article/details/104375849
2.substr()(切割字符串)
具体查看:https://blog.csdn.net/weixin_41565755/article/details/88990280
3.string::nopes(配合第一个函数使用,当没搜索到时返回的数值等于nopes)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)