如果字符串中有中文字符,而我們想取得固定長度字符串就頗為麻煩,如果給出的字符串長度大於給出的長度,則在子串的末端加上“..”。 避免出現半個漢字的情況。
程序1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EncodingConsole
{
class Program
{
private static string getLeftSubString(string content, int length)
{
Encoding encoding = Encoding.GetEncoding("gb2312");
StringBuilder sb = new StringBuilder();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EncodingConsole
{
class Program
{
private static string getLeftSubString(string content, int length)
{
Encoding encoding = Encoding.GetEncoding("gb2312");
StringBuilder sb = new StringBuilder();
byte[] bytes = new byte[length];
bytes = encoding.GetBytes(content);
if (length % 2 == 0)
{
sb.Append(encoding.GetString(bytes, 0, length));
}
else
{
sb.Append(encoding.GetString(bytes, 0,
length - 1));
sb.Append("..");
}
return sb.ToString();
}
static void Main(string[] args)
{
string outStr = "";
string input="哈啊啊好好";
outStr = getLeftSubString(input,3);
Console.WriteLine(outStr);
Console.ReadLine();
}
}
}
return sb.ToString();
}
static void Main(string[] args)
{
string outStr = "";
string input="哈啊啊好好";
outStr = getLeftSubString(input,3);
Console.WriteLine(outStr);
Console.ReadLine();
}
}
}
程序2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EncodingConsole
{
class Program
{
private static string getLeftSubString(string content,int length)
{
Encoding encoding = Encoding.GetEncoding("gb2312");
StringBuilder sb = new StringBuilder();
byte[] bytes = new byte[length];
bytes = encoding.GetBytes(content);
if (length % 2 == 0)
{
sb.Append(encoding.GetString(bytes, 0, length));
}
else
{
&nbs sb.Append(encoding.GetString(bytes, 0, length - 1));
sb.Append("..");
}
return sb.ToString();
}
static void Main(string[] args)
{
string outStr = "";
string input="哈啊啊好好";
outStr = getLeftSubString(input,3);
Console.WriteLine(outStr);
Console.ReadLine();
}
}
}