C++ | 不用额外空间反转句子

描述
给定一个字符串,逐个翻转字符串中的每个单词。
说明
单词的构成:无空格字母构成一个单词
样例
给出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;
    }
    //s=“ylf nac i”
    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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值