本帖最后由 wayne7sk 于 2014-3-22 20:46 编辑
- public class Hm
- {
- public static void main(String[] args)
- {
- System.out.println(method("HM黑马",3));
- }
-
- public static String method(String str,int a)
- {
- String str1=null;
- if(str!=null)
- {
- byte[] by = str.getBytes();
- if(by.length <= a)
- {
- str1 = str;
- }
- else
- {
- if (a>0)
- {
- str1=new String(by,0,a);
- int len = str1.length();
- //此处,我理解为len=a+1,
- //而在下面的代码中如果将len-1代替为a就会出现StringIndexOutOfBoundsException异常
- //为什么用len-1就可以而a不可以呢?
- if(str.charAt(len-1)!=str1.charAt(len-1))
- {
- if (length<2)
- {
- str1=null;
- }
- else
- {
- str1= str1.substring(0, len-1);
- }
-
- }
-
- }
-
- }
- }
-
- return str1;
-
-
- }
-
- }
复制代码 问题在注解处。谢谢了
|