Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9529

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

$
0
0
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

Viewing all articles
Browse latest Browse all 9529

Trending Articles