【问题标题】:Write a method to replace all spaces in a string with '%20'?写一个方法用'%20'替换字符串中的所有空格?
【发布时间】:2015-02-13 00:47:59
【问题描述】:

我有一个关于编程问题的问题,来自 Gayl Laakmann McDowell 的《破解代码访谈》,第 5 版。

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

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();
}

【问题讨论】:

  • 变化,因为它给出了错误的结果?还是有所不同,因为这是一个正确的答案,但与书中的答案不同?
  • 这应该刚刚工作,请说明它是如何工作的,replaceAll(" ", "%20"); 会将所有单个空格替换为%20 但如果您正在这样做来编码 URL,请查看 URLEncoder
  • sentence = sentence.replace(" ", "%20");?
  • @arynaq 因为这不是书中的答案(而且不正确),而且书中的答案要复杂得多:stackoverflow.com/questions/10007631/…
  • 您的句子将以“%20”开头。

标签: java arrays string char


【解决方案1】:

在这个循环中,程序在每个单词前添加%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();
}

【讨论】:

  • 对于您的第二个代码示例:您还可以使用第一个单词初始化 StringBuilder:StringBuilder sentence = new StringBuilder(word[0]);
  • 好主意,完成了,谢谢@Tom!顺便说一句,我想你可能会喜欢Code Review
  • 我已经有一个帐户,但在那里回答需要更多的时间我通常没有:(。
【解决方案2】:

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

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】:

    书中的问题说:

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

    它还表示您作为输入获得的 char 数组的长度足以容纳修改后的字符串。
    通过使用splitStringBuffer,您可以使用额外的 O(n) 空间。这就是为什么您的答案变化很大且不正确的原因(除了添加额外的"%20")。

    【讨论】:

      【解决方案4】:

      最简单的方法之一:

      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] );
              }
          }
      }
      

      【讨论】:

        【解决方案5】:
        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
        }
        

        【讨论】:

        • 答案应该总是带有一些解释,所以如果你能补充一点,那就太好了!谢谢!
        【解决方案6】:

        我正在使用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

        【讨论】:

          【解决方案7】:
          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;
          }
          

          【讨论】:

            猜你喜欢
            • 2012-04-17
            • 1970-01-01
            • 1970-01-01
            • 2012-01-31
            • 1970-01-01
            • 2018-07-09
            • 2012-01-11
            • 1970-01-01
            • 2011-04-17
            相关资源
            最近更新 更多