编写一个方法来替换字符串中的所有空格'%20'?

时间:2014-12-14 23:24:37

标签: java arrays string char

我对Gayl Laakmann McDowell第5版“Cracking The Code Interview”一书中的编程问题提出疑问。

我不确定我的答案有什么问题?它与书中给出的答案有很大的不同。

public String replace(String str){

   String[] words = str.split(" ");
   StringBuffer sentence = new StringBuffer();

   for(String w: words){
      sentence.append("%20");
      sentence.append(w);
   }

  return sentence.toString();
}

7 个答案:

答案 0 :(得分:6)

书中的问题说:

  

注意:如果在Java中实现,请使用字符数组   您可以就地执行此操作。

它还说你输入的char数组足够长,可以保存修改后的字符串 通过使用splitStringBuffer,您可以使用额外的O(n)空间。这就是为什么你的答案变化很大而且不正确(除了增加额外的"%20")。

答案 1 :(得分:5)

在此循环中,程序会在每个单词之前添加%20

   for(String w: words){
      sentence.append("%20");
      sentence.append(w);
   }

这会产生不正确的结果,例如a b会产生%20a%20b

有一个更简单的解决方案:

public String replace(String str) {
    return str.replaceAll(" ", "%20");
}

或者,如果你真的不想使用.replaceAll,那么写一下:

public String replace(String str) {
    String[] words = str.split(" ");
    StringBuilder sentence = new StringBuilder(words[0]);

    for (int i = 1; i < words.length; ++i) {
        sentence.append("%20");
        sentence.append(words[i]);
    }

    return sentence.toString();
}

答案 2 :(得分:1)

您还可以执行以下操作,替换任何空格

String s = "Hello this is a       string!";
System.out.println(replaceSpace(s, "%20"));


public static String replaceSpace(String s, String replacement) {
    String ret = s.replaceAll("  *", replacement);
    return ret;
}

给出

Hello%20this%20is%20a%20string!

答案 3 :(得分:1)

最简单的方法之一:

public void replaceAll( String str )
{
    String temp = str.trim();

    char[] arr = temp.toCharArray();
    StringBuffer sb = new StringBuffer();

    for( int i = 0; i < arr.length; i++ )
    {
        if( arr[i] == ' ' )
        {
            sb.append( "%20" );
        }
        else
        {
            sb.append( arr[i] );
        }
    }
}

答案 4 :(得分:0)

private static String applyReplaceOperationWithCount(String str) {
    if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
        return str;
    }
    char[] strChar = str.toCharArray(); 

    int count = 0; //count spaces in the string to recalculate the array length
    for (char c : strChar) {
        if (c == ' ') {
            count++;
        }
    }

    if (count == 0) { // if there are no spaces in the string, return it 
        return str;
    }

    int length = strChar.length;
    char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
    int index = 0;
    for (char c : strChar) { 
        if (c != ' ') { // if char is not a space just push it in the next available location
            newChar[index++] = c;
        } else { // if char is a space just push %,2,0 
            newChar[index++] = '%';
            newChar[index++] = '2';
            newChar[index++] = '0';
        }
    }
    return new String(newChar); // convert the new array into string
}

答案 5 :(得分:0)

我正在使用matchesreplaceAll,效果很好。

public class ReplaceSpaces {

public static void main(String[] args) {

    String text = " Abcd olmp  thv ";

    if(text.matches(".*\\s+.*")){
        System.out.println("Yes I see white space and I am replacing it");
        String newText = text.replaceAll("\\s+", "%20");
        System.out.println(newText);
    }
    else{
        System.out.println("Nope I dont see white spaces");
    }
}
}

输出 Yes I see white space and I am replacing it %20Abcd%20olmp%20thv%20

答案 6 :(得分:0)

public static String replaceSpaceInString(String string,String toreplace){
    String replacedString = "";
    if(string.isEmpty()) return string;
    string = string.trim();
    if(string.indexOf(" ") == -1)return string;
    else{
        replacedString = string.replaceAll("\\s+",toreplace);
    }
    return replacedString;
}