簡體   English   中英

編寫一個方法來用'%20'替換字符串中的所有空格?

[英]Write a method to replace all spaces in a string with '%20'?

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

書中的問題說:

注意:如果在Java中實現,請使用字符數組,以便您可以就地執行此操作。

它還說你輸入的char數組足夠長,可以保存修改過的字符串。
通過使用splitStringBuffer您可以使用額外的O(n)空間。 這就是為什么你的答案變化很大而且不正確(除了增加額外的"%20" )。

在這個循環中,程序在每個單詞之前添加%20

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

這將產生不正確的結果,例如對於ab ,它將給出%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();
}

您還可以執行以下操作,替換任何空格

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!

最簡單的方法之一:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM