SoFunction
Updated on 2025-03-06

How to count the number of Chinese characters in C# strings

How to get the number of Chinese characters in a string from C#? In C#, regular expressions are used to judge Chinese characters from strings and then count them to obtain the number of Chinese characters in the string.

Let's look at this code first:

Copy the codeThe code is as follows:

//First refer to the namespace
using ;

//Define a function to return the number of Chinese characters in the string
public static int GetHanNumFromString(string str)
{
    int count = 0;
    Regex regex = new Regex(@"^[\u4E00-\u9FA5]{0,}$");

    for (int i = 0; i < ; i++)
    {
        if ((str[i].ToString()))
        {
            count++;
        }
    }

    return count;
}


Code description:
1. The Unicode character is encoded between \u4E00 and \u9FA5, so it is used to represent the regular matching range of Chinese characters.
2. The string can be indexed directly. The data type of the value obtained by the index is char, so str[i].ToString() is to convert char into a string again.
3. Using Regex's IsMatch method, you can determine whether the string matches the given regular expression. If the match is successful, it returns True, otherwise it is False.