zoukankan      html  css  js  c++  java
  • 反转一句话(仅反转各单词的顺序)

    一、目的:将字符串"I am  a   programmer" 反转为 "programmer   a  am I".

    二、具体实现
    方法1,使用split函数
    思路:将str用一个空格分割成数组,然后将数组"从尾至头"输出;输出时有一个小问题需要注意,由于分割得到数组的过程去掉了原字符串中(数组长度数-1)个空格,所以输出时要补上。

    private static void reverse()

        string str = "I am  a   programmer";
        string[] arr = str.Split(' ');

        for (int i = arr.Length - 1; i >= 0; i--)
        {
            Console.Write(arr[i] + " ");
        }

        Console.WriteLine("");
    }

    方法2,不使用split函数
    思路:将str"从尾至头"一个一个地遍历,如果当前char是" "或' ',就先输出之前记录的非空字串,然后输出当前的字符(一个空格);否则,就先记录当前字符。这里也有一点需要注意,就是“有可能最后temp中还保存有非空格的字符,但还没有输出”,所以最后还需要再输出一次temp(这里有一个技巧,就是不用再判断temp是否为空,因此如果temp为空话输出也不会对结果有什么影响)。

    private static void reverse()

        string str = "I am  a   programmer";  
        string temp = "";

        for (int i = str.Length - 1; i >= 0; i--)
        {
            if (str[i] == ' ')
            {
                Console.Write(temp);
                Console.Write(" ");

                temp = "";
            }
            else
            {
                temp = str[i] + temp;
            }
        }

        Console.Write(temp);
        Console.WriteLine("");
    }

  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/aspsmile/p/1260971.html
Copyright © 2011-2022 走看看