java面试题

来源:互联网 发布:java 获取 时间 编辑:程序博客网 时间:2024/06/11 09:25

 最近忙着找工作,须便在网上找找java笔试题看看,结果发现网上的下面这套题答案有问题。

编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

他们的我就不贴出来了。有兴趣可以到网上找找。

下面是我写的一个,有错误,还望高人指出。

 

import java.util.Scanner;

class SplitString ...{
    
public static String subString(String str, int n) ...{
        
int m = 0;
        String chr 
= "";
        
final String PATTERN = "^([/u4e00-/u9fa5]*)$" ;
        
if (n <= 0...{
            
return "";
        }


        
for (int i = 0; i < str.length(); i++...{
            
if (m < n) ...{
                chr 
= str.substring(i, i + 1);
                
if (chr.matches(PATTERN)) ...{
                    m 
+= 2;
                }
 else ...{
                    m
++;
                }

            }
 else ...{
                
return chr.matches(PATTERN) ? ((m - n) >= 1 ? str.substring(0,
                        i 
- 1) : str.substring(0, i)) : str.substring(0, i);
            }

        }

        
return "";
    }

}


public class TestSplitString ...{
    
public static void main(String[] args) ...{
        String testString 
= new String("a我f在dfdsa中dfd国城fd里");
        System.out.println(
"在字符串:"" + testString + ""中取:n(字节), 请输入字节数:");
        Scanner in 
= new Scanner(System.in);
        
int n = in.nextInt();
        System.out.println(
"取'" + n + "'个字节");
        System.out.println(
"结果为:" + SplitString.subString(testString, n));
    }

}

原创粉丝点击