1

你能建议我在哪里犯错:

  public static char[] replaceSpaces(String string){
    int length = string.length();
    int spaceCount = 0;
    for(int i =0; i<=length-1;i++){if(string.charAt(i)==' '){spaceCount++;}}

    int index = length + spaceCount*2;
    char[] charString = new char[index];
    int k=0;
    for(int i=0;i<index-1;i++){

        if(string.charAt(k) == ' '){
            charString[i] = '%';
            charString[i+1] = '2';
            charString[i+2] = '0';
            i = i +2;
            k=k+1;}
        else
            charString[i] = string.charAt(k);
            k++;
    }
    return charString;}

}

它输出wa%20cf而我想要“wa%20dcf”作为输出。基本上我用“%20”替换每个空格。此外,此代码不适用于两个或多个空格。

4

3 回答 3

5

为什么要编写自己的方法?

String yourString = "my test string".replace(" ", "%20");
于 2013-07-10T23:19:17.413 回答
1

你应该只使用String.replace()

简单的错误,您忘记了 else 语句的大括号,所以要么这样做

else
{
    charString[i] = string.charAt(k);
    k++;
}

或因为k= k+1相当于将k++您的 for 更改为此

for(int i = 0; i < index; i++) // also change your index 
{
    if(string.charAt(k) == ' ')
    {
        charString[i] = '%';
        charString[i+1] = '2';
        charString[i+2] = '0';
        i = i +2;
    }
    else
    { // these braces are not needed now but inculde them to make my 
      // point above valid
        charString[i] = string.charAt(k);
    }
    //increment every time
    k++;
}

这将解决您遇到的两个问题

于 2013-07-10T23:41:55.807 回答
0

您可以使用一个 replaceAll() 方法:

         String newString = string.replaceAll(" ","%20");
于 2013-07-10T23:26:17.503 回答