一种巧妙的反转字符串的方法及思考过程

如题,需求是反转字符串,当然啦方法是有很多的,这种我觉得蛮有意思的^_^

#include <string>
#include <iostream>

using namespace std;

int main() {
    string s;
    cin>>s;
    for(int i = s.size(); i--; ) {
        cout<<s[i];
    }
    cout<<endl;
    return 0;
}
Input: abc
Output: cba

这段代码的特点是 i 是放在了判断语句中,起初我不是很能理解,不过根据输出断定了是i等于0的时候就退出了循环。经过打断点来测试,证实了这个猜测。

为了证实这个猜想,我继续写了两段简短的代码。

#include <string>
#include <iostream>
using namespace std;
int main() {
    string s;
    cin >> s;
    for (int i = s.size(), j = s.size() - 1; i--, j--;) {
        cout << s[i] << " " << s[j];
    }
    cout << endl;
    return 0;
}
Input: abc
Output: c bb a

最终的状态是:

i=1, j=0

另一段代码是:

#include <string>
#include <iostream>
using namespace std;
int main() {
    string s;
    cin >> s;
    for (int i = s.size(), j = s.size() - 1; j--, i--;) {
        cout << s[i] << " " << s[j];
    }
    cout << endl;
    return 0;
}
Input: abc
Output: c bb a (输出这部分后程序崩溃)

最终的状态是:

j=-1, i=0

第一段代码表明自减操作有返回值,且就是这个变量的值;那么为什么第二段代码中j减到0之后还会继续减少呢,之所以继续减少是因为循环还在走,之所以循环没有退出是因为这里的逗号运算符的结果取最后一个。

还有一个小细节,我不是很清楚,因为很少在实际码字中用过,那就是判断中是因为0才停止的,那么负数呢?也就是说负数直接类型转换是true还是false呢。

#include <iostream>
using namespace std;
int main() {
    if(-1) cout<<"t";
    else cout<<"f";
    return 0;
}
Output: t

紧接着我又尝试了在C#中的情况,这里无法自动将int转换成bool,只得写了一个方法。

class Program
{
    static void Main(string[] args)
    {
        string s;
        s = Console.ReadLine();
        for (int i = s.Length; isBool(i--);)
        {
            Console.Write(s[i]);
        }
        Console.WriteLine();
    }

    static bool isBool(int n)
    {
        if (n > 0) return true;
        else return false;
    }
}
Input: abc
Output: cba

总而言之,好吧我承认很Easy,不过其过程却是充满了乐趣,就喜欢这种假装探索的感觉。Bye……

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值