简体   繁体   English

使用递归从字符串的某个索引处替换字符

[英]Replacing characters at a certain index from string, using recursion

Hi im trying to create a method to remove the spaces from a word recursively. 您好,我试图创建一种方法来递归删除单词中的空格。 Ive done this so far, and im really not sure why its not working. 到目前为止,我已经做到了,我真的不确定为什么它不起作用。

public static String compact (String line)
{

    for (int x = 0 ; x < line.length () ; x++)
    {
        if (line.charAt (x) == ' ')
        {
            String newLine = line.substring (0, x) + line.substring (x);
            return compact (newLine);
        }
        else
            break;
    }
    return line;
}

This just returns the original string without removing any spaces. 这只是返回原始字符串而不删除任何空格。 Can someone please tell me what im doing wrong, thanks. 有人可以告诉我我做错了什么,谢谢。

Just remove the 只需删除

else break;  

part, because if the first character of your String is not a whitespace, the loop will terminate 部分,因为如果String的第一个字符不是空格,则循环将终止

Also replace 也更换

String newLine = line.substring (0, x) + line.substring (x);

with

String newLine = line.substring (0, x) + line.substring (x + 1);

because you are actually not removing the whitespace, but copying the whole string over and over again. 因为您实际上并不是在删除空格,而是一遍又一遍地复制整个字符串。 This is why you get a StackOverflowError . 这就是为什么您得到StackOverflowError


The method should look like this: 该方法应如下所示:

public static String compact(String line) {
    for (int x = 0; x < line.length(); x++) {
        if (line.charAt(x) == ' ') {
            String newLine = line.substring (0, x) + line.substring (x+1);
            return compact(newLine);
        }
    }
    return line;
}

You can get rid of the for loop and fix that in one line of code... 您可以摆脱for循环,并在一行代码中解决该问题。

Just use.. 只是使用..

  //changes a string "moon shine" to "moonshine"
  String newLine = line.trim().replaceAll(" +", "");
  System.out.println(newLine);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM