本實例展示了C#實現判斷字符串中是否包含中文的方法,是一個非常實用的功能,對初學者來說有一定的借鑒學習價值,具體實現方法如下:
主要功能代碼如下:
/// <summary>/// 判斷字符串中是否包含中文/// </summary>/// <param name="str">需要判斷的字符串</param>/// <returns>判斷結果</returns>public static bool HasChinese(this string str){ return Regex.IsMatch(str, @"[/u4e00-/u9fa5]");}
單元測試代碼如下:
[TestMethod()]public void HasChineseTest(){ string _chineseStr1 = "你好Word"; bool _expected1 = true; bool _actual1 = StringToolV2.HasChinese(_chineseStr1); Assert.AreEqual(_expected1, _actual1); string _chineseStr2 = "Hello World"; bool _expected2 = false; bool _actual2 = StringToolV2.HasChinese(_chineseStr2); Assert.AreEqual(_expected2, _actual2);}
測試結果如下:
新聞熱點
疑難解答