zoukankan      html  css  js  c++  java
  • 一种巧妙的反转字符串的方法及思考过程

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

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

  • 相关阅读:
    HDU 1025:Constructing Roads In JGShining's Kingdom(LIS+二分优化)
    HDU 3938:Portal(并查集+离线处理)
    HDU 1811:Rank of Tetris(并查集+拓扑排序)
    HDU 1074:Doing Homework(状压DP)
    HDU 1024:Max Sum Plus Plus(DP)
    最最最亲爱哒
    hlg-1332 买电脑 ---二分
    时间过得很快
    0514
    hlg1551Assemble--暴力求解
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6963962.html
Copyright © 2011-2022 走看看