0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

c# 全角と半角のカウント

Posted at

shift-jisのサポートがない場合。

using System;
using han_zen;
class Program
{
    static void Main(string[] args)
    {
        //usage
        Console.WriteLine("あいうえを ".getWidth());
        Console.WriteLine("" + 'ア'.isHalfWidth());
        Console.WriteLine("" + 'ア'.getWidth());
        Console.WriteLine("" + '亜'.getWidth());

        Console.WriteLine("Hello World!");
    }
}//class

namespace han_zen
{
    using System.Text.RegularExpressions;
    using System.Linq;
    static class ZenkakuExtension
    {
        static Regex ptn = _();
        static Regex _()
        {
            var range = ""
            + "a-z"
            + "A-Z"
            + "0-9"
            + "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ "
            + "ア-゙" //半角カナ
            ;
            return new Regex($"^[{range}]+$");
        }
        public static bool isHalfWidth(this string @str) => ptn.IsMatch(@str);
        public static bool isFullWidth(this string @str) => !@str.isHalfWidth();
        public static bool isHalfWidth(this char @ch) => ("" + @ch).isHalfWidth();
        public static bool isFullWidth(this char @ch) => !@ch.isHalfWidth();
        public static int getWidth(this char @ch) => @ch.isHalfWidth() ? 1 : 2;
        public static int getWidth(this string @str) => @str.Select(getWidth).Sum();

    }//class

}//namespace
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?