正規表現を使用して中国語を含む文字列の長さを計算

5954 ワード

using System;
using System.Text.RegularExpressions;
 
namespace LangZi{/*//////StringHelperの概要説明//public class StringHelper{public StringHelper(){///TODO:ここにコンストラクタロジックを追加//}
GetLength#region GetLength/*//////中国語文字を含む文字列長///C#のstringを返します.Lengthの中の文字は1ビットの統計しかしていません.したがって、2ビット///mmary>///長さを統計する文字列変数///文字列長public static int GetLength(string strSource){Regex regex=new Regex(「[/u 4 e 00-/u 9 fa 5]+」に変換するには、RegexOptions.Compiled);            int nLength = strSource.Length;
            for(int i=0; i            return nLength;        }        #endregion    }} 
中国語を含む文字列regcn=/[/u 4 e 00-/u 9 fa 5]/;「xxx-xxxxxx」などの電話番号を一致させる:regphone=/^[0-9]/-[0-9]$/;携帯番号:regmobile=/^13[0-9]{8}/;  
using System;
using System.Text.RegularExpressions;

namespace LangZi
{
    /// <summary>
    /// StringHelper  。
    /// </summary>
    public class StringHelper
    {
        public StringHelper()
        {
            //
            // TODO:  
            //
        }
        #region GetLength
        /// <summary>
        ///  
        /// C#  string.Length 1 , 2 
        /// </summary>
        /// <param name="strSource"> </param>
        /// <returns> </returns>
        public static int GetLength(string strSource)
        {
            Regex regex = new Regex("[/u4e00-/u9fa5]+", RegexOptions.Compiled);
            int nLength = strSource.Length;

            for (int i = 0; i < strSource.Length; i++)
            {
                if (regex.IsMatch(strSource.Substring(i, 1)))
                {
                    nLength++;
                }
            }

            return nLength;
        }
        #endregion
    }
}

次の操作を行います.
コピー
保存#ホゾン#
string source;
int length;

source = "123";
length = LanZi.StringHelper.GetLength(source);
Console.WriteLine(length); // 3

source = "12 ";
length = LangZi.StringHelper.GetLength(source);
Console.WriteLine(length); // 4  , 2

土人は最も土の方法を使って、自分の目標を実現することを求めて、銀河兄のC#の中の文字の符号化の問題の1文を見て、もっと良いもっと完璧な方法があることを発見しました:
コピー
保存#ホゾン#
using System;
using System.Text;

namespace LangZi
{
    /// <summary>
    /// StringHelper  。
    /// </summary>
    public class StringHelper
    {
        public StringHelper()
        {
            //
            // TODO:  
            //
        }
#region GetLength
        /// <summary>
        ///  
        /// C#  string.Length 1 , 2 
        /// </summary>
        /// <param name="strSource"> </param>
        /// <returns> </returns>
        public static int GetLength(string strSource)
        {
             return Encoding.GetEncoding("GB18030").GetBytes(strSource).Length; 
        }
        #endregion
    }

コピー
保存#ホゾン#
public static int GetLength(string strSource)
{
    return Regex.Matches(strSource, "[/u4e00-/u9fa5]").Count + strSource.Length;
}

コピー
保存#ホゾン#
string str = " "; 
int length = str.ToCharArray().Length;