C#小知识之中英文转换、去空格


一、中英文转换

1、安装NPinYin

img

2、编写代码

1
2
3
4
5
6
7
8
string str = "这里是测试的中文字符串";
string str1 = Pinyin.GetChineseText(str);
string str2 = Pinyin.GetInitials(str);
string str3 = Pinyin.GetPinyin(str);

Console.WriteLine("取和拼音相同的汉字列表:" + str1);
Console.WriteLine("取中文文本的拼音首字母:" + str2);
Console.WriteLine("取中文文本的拼音:" + str3);

3、运行效果

img

二、去空格

1、编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string strWithSpaces = " this is a test string with spaces ";

// 字符串行数Trim()可以去掉字符串前后的空格
Console.WriteLine(strWithSpaces.Trim());


// 使用字符串的Replace()函数可以去掉字符串中间及前后的空格
Console.WriteLine(strWithSpaces.Replace(" ", ""));


// 然而,当字符串中含转义字符(如\r, \t, \n)时,Replace函数输出的结果中还是有空格,如:
string strWithSpaces2 = "this\n is\r a\t test\n string\r with\t spaces";
Console.WriteLine(strWithSpaces2.Trim());

// 此时当然可以用多个Replace函数来替换这些空格,但稍显麻烦;可以考虑用正则表达式方法Regex.Replace()和匹配符\s(匹配任何空白字符,包括空格,制表符,换页符等,与[\f\n\t\r\v]等效),如:
Console.WriteLine(Regex.Replace(strWithSpaces2, @"\s", ""));

2、运行效果

img

三、中文转英文 + 去掉空格

1、编写代码

1
2
3
string str = "这里是测试的中文字符串";
string strFinal = Regex.Replace(Pinyin.GetPinyin(str).Trim(), @"\s", "");
Console.WriteLine("终极优化:" + strFinal);

2、运行效果

img

参考链接

如何去掉C#字符串中的所有空格

npinyin

遇到此问题做此记录,如有帮助,欢迎点赞关注收藏!


文章作者: GoodTimeGGB
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 GoodTimeGGB !
评论
  目录