2.1确定一个char包含何种字符

知识点:

1.char.IsControl

2.char.IsPunctuation

3.char.IsSurrogate

4.char.IsWhitespace

5.char.IsDigit

6.char.IsNumber

7.char.IsSeparation

8.char.IsSymbol

 

问题:

有一个char类型的变量,希望确定其中包含的字符是字母、一位数、数字、标点符号、控制字符、分隔符号、空白符还是替代字符。类似地,可能有一个string变量,想确定这个串中某个或多个位置上是何种字符。

解决方案

要确定一个char的值,可以使用System.Char结构的内置静态方法,如下所示:

1.char.IsControl

2.char.IsPunctuation

3.char.IsSurrogate

4.char.IsWhitespace

5.char.IsDigit

6.char.IsNumber

7.char.IsSeparation

8.char.IsSymbol

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace _02确定一个Char包含何种字符

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("请输入一个字符:");

            string symbol = Console.ReadLine();

            CharKind ck = GetCharKind(Convert.ToChar(symbol));

            Console.WriteLine(ck);

            string symbol1= Console.ReadLine();

            int position=Convert.ToInt32(Console.ReadLine());

            CharKind ck1 = GetCharKindInString(symbol1, position);

            Console.WriteLine(ck1);

            Console.ReadKey();

        }

        public static CharKind GetCharKind(char theChar)

        {

            if (char.IsLetter(theChar))

            {

                return CharKind.Letter;

            }

            else if (char.IsNumber(theChar))

            {

                return CharKind.Number;

            }

            else if (char.IsPunctuation(theChar))

            {

                return CharKind.Punctuation;

            }

            else

            {

                return CharKind.Unknown;

            }

        }



        //判断字符串中某个位置的字符类型

        public static CharKind GetCharKindInString(string theString, int CharPosition)

        {

            if (char.IsLetter(theString, CharPosition))

            {

                return CharKind.Letter;

            }

            else if (char.IsNumber(theString, CharPosition))

            {

                return CharKind.Number;

            }

            else if (char.IsPunctuation(theString, CharPosition))

            {

                return CharKind.Punctuation;

            }

            else

            {

                return CharKind.Unknown;

            }

        }

    }



    public enum CharKind

    {

        Letter,

        Number,

        Punctuation,

        Unknown

    }

}
View Code

 


验证结果

1 8 Number

你可能感兴趣的:(char)