C#——擴展.NET Framework基本類型的功能DEMO

問題描述 

 編寫一個靜態類MyExtensions,擴展.NET Framework基本類型的功能。

1)定義一個擴展方法IsPalindrome,方法定義爲:

public static bool IsPalindrome(this string str)

它擴展string類的功能,用於判斷字符串是否爲迴文(指順讀和倒讀內容都一樣的文本)。

2)定義一個擴展方法ReverseDigits,允許int將自己的值倒置,例如將整型1234調用ReverseDigits,返回結果爲4321。

測試類如下:

class Program
{
    static void Main()
    {
            string s = "abc";
            Console.WriteLine($"'{s}' is {(s.IsPalindrome() ? "" : "not")} palindrome");
            s = "abcba";
            Console.WriteLine($"'{s}' is {(s.IsPalindrome() ? "" : "not")} palindrome");
            int i = 1234;
            Console.WriteLine($"Reverse of {i} is {i.ReverseDigits()}");
    }
}

源代碼 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Homework7
{
    /**
     編寫一個靜態類MyExtensions,擴展.NET Framework基本類型的功能。
    1)定義一個擴展方法IsPalindrome,方法定義爲:
        public static bool IsPalindrome(this string str)
    它擴展string類的功能,用於判斷字符串是否爲迴文(指順讀和倒讀內容都一樣的文本)。
    2)定義一個擴展方法ReverseDigits,允許int將自己的值倒置,例如將整型1234調用ReverseDigits,返回結果爲4321。
    */
    static class MyExtensions {
        public static Boolean IsPalindrome(this string str) {
                for (int i = 0; i < (str.Length / 2); i++) //只需要判斷前一半(len/2)長度就好了
                {
                    if (str[i] != str[str.Length - 1 - i]) //判斷是否爲迴文數;
                    {
                        return false;
                    }
                }
                return true;
        }

        //本方法允許任何整型返回倒置的副本,例如將整型1234調用ReverseDigits,返回結果爲4321。 
        public static int ReverseDigits(this int i)
        {
            //把int 翻譯爲string 然後獲取所有字符    
            char[] digits = i.ToString().ToCharArray();

            //反轉數組中的項    
            Array.Reverse(digits);

            //放回string    
            string newDigits = new string(digits);

            //最後以int返回修改後的字符串    
            return int.Parse(newDigits);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            string s = "abc";
            Console.WriteLine($"'{s}' is {(s.IsPalindrome() ? "" : "not")} palindrome");
            s = "abcba";
            Console.WriteLine($"'{s}' is {(s.IsPalindrome() ? "" : "not")} palindrome");
            int i = 1234;
            Console.WriteLine($"Reverse of {i} is {i.ReverseDigits()}");
        }
    }
}

運行結果

參考文章

http://bbs.bccn.net/thread-463732-1-1.html

https://shentuzhigang.blog.csdn.net/article/details/89713050

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章