日期:2014-05-18 浏览次数:20966 次
//用C#实现一个:
static string GetSubString(string str, int byteCount)
{
int count = 0;
string result = string.Empty;
foreach (char ch in str)
{
count += System.Text.Encoding.Default.GetByteCount(ch.ToString());
if (count > byteCount) break;
result += ch.ToString();
}
return result;
}
static void Main(string[] args)//调用
{
string str = "我ABC汉DEF";
for (int i = 1; i < 10; i++)
{
Console.WriteLine("截出"+i+"个字节:");
Console.WriteLine(GetSubString(str, i));
}
}
/*输出结果:
截出1个字节:
截出2个字节:
我
截出3个字节:
我A
截出4个字节:
我AB
截出5个字节:
我ABC
截出6个字节:
我ABC
截出7个字节:
我ABC汉
截出8个字节:
我ABC汉D
截出9个字节:
我ABC汉DE
*/
------解决方案--------------------
public class Test {
/**
* @param args
*/
public void output(int count,String str)
{
int index=0;
boolean flag=false;
for(int i=0;i<str.length()&& index<count;i++)
{
char c=str.charAt(i);
if(c>=0 && c<=255)
{
flag=true;
index++;
System.out.println(c);
}
if(flag==false)
{
index+=2;
if(index<=count)System.out.println(c);
}
flag=false;
}
}
public static void main(String[] args) {
Test t=new Test();
t.output(6,"ab@毕AKDJSD");
}
}