C#截取字符串是如何执行的呢?这个在实际工作中我们经常会遇见这样的类似应用问题,那么具体的实施是什么呢?下面就向你介绍C#截取字符串的一个实例:
C#截取字符串应用:用C#截取指定长度的中英文混合字符串
我们常做的一件事情,就是在文章系统中,截取一定长度的文章标题,超过指定长度,就加“...”
如两个字符串:
string str1 = "中国人要啊abc呀~";
string str2 = "1中国人23456abc呀~";
- 1.
- 2.
C#截取字符串程序输出:
str1 = "中国人要...";
str2 = "1中国人2...";
- 1.
- 2.
即要把中英文混合的字符串,在截取后,长度要一致,即8个字节的长度(不包括三个点),而且不能出现中文被从中间截断的情况。于是写了个方法:
public static string getStr(string s,int l)
{
string temp = s ;
if (Regex.Replace(temp,
"[\u4e00-\u9fa5]","zz",
RegexOptions.IgnoreCase).Length<=l)
{
return temp;
}
for (int i=temp.Length;i>=0;i--)
{
temp = temp.Substring(0,i);
if (Regex.Replace(temp,
"[\u4e00-\u9fa5]","zz",
RegexOptions.IgnoreCase).Length<=l-3)
{
return temp + "";
}
}
return "";
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
调用:
string content = "中国人啊abc呀呀呀呀";
content = getStr(content,13);
- 1.
- 2.
C#截取字符串的相关应用就向你介绍到这里,希望对你了解和学习C#截取字符串的操作有所帮助。
【编辑推荐】