【C#】String and Number Reverse

由于反转的概念在我前面的文章已提到~ 所以这边就不多做说明~

简单来说~ 就是将字串"123" ~ 变成 "321" 或将整数-1234 变成-4321


学习目标: C# Reverse 实务

学习难度: ☆☆☆


字串反转


using System;namespace ConsoleApp1{    class MainProgram    {        static string Reverse(string input)        {            char[] Array = input.ToCharArray();//将string塞入CharArray            string output = String.Empty;            for (int i = Array.Length - 1; i >= 0; i--)            {                output += Array[i];            }            return output;        }        static void Main()        {            string input = Console.ReadLine();            Console.WriteLine(Reverse(input + "\n"));        }    }}

整数反转


using System;namespace ConsoleApp1{    class MainProgram    {        static int Reverse(int input)        {            int output = 0;            bool negative = false;            if (input == 0)            {                return 0;            }            else if (input > 0)            {                negative = false;            }            else if (input < 0)            {                input = Math.Abs(input);                negative = true;            }            while (input > 0) /*这个迴圈是Reverse的核心*/            {                output = output * 10 + input % 10;                input /= 10;            }            if (negative == true)            {                output *= -1;            }            return output;        }        static void Main()        {            Console.WriteLine(Reverse(-6532));        }    }}

参考资料:


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章