有一次面试遇到一个算法题,题目如题,比如字符串 String s = "Hello   world I   love    you". s中的单词之间有若干个空格。要求只去掉这些空格中的一个,其余的保留,返回删除一个空格后的字符串。请高手赐教!谢了!

解决方案 »

  1.   

    呵呵,s.replaceAll("  +", " ");
    NO 算法.
      

  2.   

    public class Test {
    public static void main(String[] args) {
    String s = "Hello  world I  love    you";
    s=s.replaceAll(" ", "");;
    System.out.println(s);
    }
    }
      

  3.   

    不好意思看错了
    public class Test {
    public static void main(String[] args) {
    String s = "Hello  world I  love    you";
    s=s.replaceFirst(" ", "");;
    System.out.println(s);
    }
    }
      

  4.   


    public class Test{    public static void main(String[] args) {
         String s = "Hello  world I  love    you";
    System.out.println(del(5,s));
        }
        public static String del(int index,String str){
         StringBuilder sb = new StringBuilder(str);
         sb.deleteCharAt(index);
         return sb.toString();
        }}
      

  5.   

    up,要知道空格出现出的索引值index,然后调用del()即可
      

  6.   

    String中有很多方法的,replaceAll或deleteCharAt或substring都可以实现。
      

  7.   

    String s = "Hello  world I  love    you";  
    System.out.println(s);  
    System.out.println(s.replaceAll("\\s(\\s*)", "$1"));  好像你还有另外一个帖子吧,我回复了,为何还不结贴?
      

  8.   

    呵呵,写了个没采用正则表达式的版本。public class Test { public static void main(String[] args) {
            
            String s = "Hello  world I  love    you";
            char[] chs = s.toCharArray();
            boolean findSpace = false;
            int offset = 0;
            for(int i = 0; i < chs.length; i++) {
                if(chs[i] == ' ') {
                    if(findSpace) {
                        continue;
                    }
                    findSpace = true;
                } else {
                    findSpace = false;
                }
                chs[offset++] = chs[i];
            }
            System.out.println(new String(chs, 0, offset));
        }
    }
      

  9.   

    谢谢大家了。我已经在另外一个贴子上结贴了!java2000_net,我已经给分了哈。谢了。能不能解释一下你那个正则写法的意思