关于几个 字符串 操作的问题 1. 怎么将ascii码转成字符2.求子串位置 ,例如 : this is a cup 如何求出 is 的首次的位置 , 返回 3 3.如何去除字符左边或右边空格4.删除子串 ,例如 :this is a cup 如何从第2个字符开始 删除 4个字符

解决方案 »

  1.   

    1.char(65);
    2.String s = "this is a cup";
      int index = s.indexOf("is");
    3.**.trim();
    4.StringBuffer sb = new StringBuffer(s);
      sb.delete(2, 2+4);
      

  2.   

    String(byte[] bytes, String charsetName) 
    String.indexOf()
    String.trim()
    String.substring()
      

  3.   

    2.求子串位置 ,例如 : this is a cup 如何求出 is 的首次的位置 , 返回 3 
    题错了,应该返回2才对
    3 如何去除字符左边或右边空格
    String teststr = "   ddsa   ";
    char[] ch = teststr.toCharArray();
    ----------------左trim()空格-------------------
    for(int i=0;i<ch.length;i++){
    if(ch[i]!=' '){
    char[] bufch = new char[ch.length-i];
    System.arraycopy(ch, i, bufch, 0, ch.length-i);
    System.out.println(new String(bufch));
    break;
    }
    }
    ----------------右trim()空格-------------------
    for(int i=ch.length-1;i>-1;i--){
    if(ch[i]!=' '){
    char[] bufch = new char[i];
    System.arraycopy(ch, 0, bufch, 0, i);
    System.out.println(new String(bufch));
    break;
    }
    }
      

  4.   

    应该是 char c = (char)65;----左trim----
    String s = " abc ";
    s = s.replaceAll("^ +", "");----右trim----
    String s = " abc ";
    s = s.replaceAll(" +$", "");
      

  5.   

    public static void main(String[] args) {
    String s = "  \n abc  \n";
    System.out.println(rightTrim(s));
    System.out.println(leftTrim(s));}public static String leftTrim(String str) {
    int index = 0;
    while (str.charAt(index) <= ' ') {
    index++;
    }
    return str.substring(index);
    }public static String rightTrim(String str) {
    int index = str.length() - 1;
    while (str.charAt(index) <= ' ') {
    index--;
    }
    return str.substring(0, index + 1);
    }
      

  6.   


    String str="  123456   ";
    去左空格 str=str.replaceAll("^\\s*","");
    去右空格 str=str.replaceAll("\\s*$","");