日期:2014-05-18  浏览次数:20659 次

一个关于截取字符串的面试题!
编程:编写一个截取字符串的函数,输入一个字符串和字节数,输出按字节书截取的字符串,但是要保证汉字不能截半个,,如“我ABC”,4 应该截取“我AB”,输入“我ABC汉DEF”,6 然后输出“我ABC”,而不是半个汗字;
---------------------------------
周五下午做的面试题,回来一直在想!大家帮我看看,顺便带上方法注释!

------解决方案--------------------
我在别的地方找了一段代码
public static String substring(String str, int toCount,String more) 

int reInt = 0; 
String reStr = ""; 
if (str == null) 
return ""; 
char[] tempChar = str.toCharArray(); 
for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++)

String s1 = str.valueOf(tempChar[kk]); 
System.out.print(s1);
byte[] b = s1.getBytes(); 
reInt += b.length; 
reStr += tempChar[kk]; 

if (toCount == reInt || (toCount == reInt - 1)) 
reStr += more; 
return reStr;
}
------解决方案--------------------
public static string SubstringByByte(string str, int byteLength)
{
char[] strs = str.ToCharArray();
string strings = null;
if (byteLength == 0)
return strings;
foreach (char temp in strs)
{
byte[] bytes = Encoding.UTF8.GetBytes(temp.ToString());
strings += temp.ToString();
byteLength = byteLength - bytes.Length;
if (byteLength <= 0)
break;
}
return strings;
}
虽然有点麻烦,不过好像能行
------解决方案--------------------
C# code
//用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");

}

}