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

如题,需求是反转字符串,当然啦方法是有非常多的,这样的我认为蛮有意思的^_^

#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……

原文地址:https://www.cnblogs.com/gavanwanggw/p/6963962.html