简体   繁体   English

如何递归获取输入字符串并返回每个字符重复的字符串?

[英]How to recursively take an input string and return a string with each character repeated?

Basically I have an assignment that requires me to write a method called stutter . 基本上我有一个任务,要求我编写一个名为stutter的方法。 The stutter method is supposed to take an input String s and return the string with each character repeated. stutter方法应该接受一个输入String并返回每个字符重复的字符串。 For example, if the input string was "help" then the result of running this method should be "hheellpp". 例如,如果输入字符串是“help”,则运行此方法的结果应为“hheellpp”。 I have tried a bunch of different things and can't get it to work. 我尝试了很多不同的东西,无法让它发挥作用。 Here is my code: 这是我的代码:

import java.util.*;

public class Stutter {  
    static String stutterString = "";

    public static String stutter ( String s ) {
        char ch = s.charAt (0);
        String tempString = String.valueOf ( ch );
        if ( s.length() == 0 ) {
            return stutterString;
        } else {
            stutterString += tempString + tempString;
            return stutter ( s.substring (1) );
        }
    }

    public static void main ( String [] args ) {
        Scanner inputScanner = new Scanner ( System.in );
        System.out.println ( "What word would you like to stutter?" );
        String userInput = inputScanner.next();     
        inputScanner.close();       
        System.out.println ( stutter ( userInput ) );
    }
}

I get an error that I'm not sure what to do with. 我得到一个错误,我不知道该怎么做。 This is the error: 这是错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)
    at Stutter.stutter(Stutter.java:12)
    at Stutter.stutter(Stutter.java:23)
    at Stutter.main(Stutter.java:41)

Any help would be appreciated. 任何帮助,将不胜感激。 This isn't a huge program. 这不是一个庞大的计划。 As you can see, I've posted the entire Stutter class that I'm using. 如您所见,我已经发布了我正在使用的整个Stutter类。 It's just bugging me because I'm sure there is a simple fix to this, but I'm not seeing it. 这只是困扰我,因为我确信有一个简单的解决方案,但我没有看到它。

You need to change this line 你需要改变这一行

char ch = s.charAt (0);

to

char ch = s.length() > 0 ? s.charAt(0) : ' ';

And your code will work as expected. 您的代码将按预期工作。

A better and clearer solution would be: 一个更好,更清晰的解决方案是:

if (s.length() == 0) {
    return stutterString;
} else {
    char ch = s.charAt(0);
    String tempString = String.valueOf(ch);
    stutterString += tempString + tempString;
    return stutter(s.substring (1));
}

What word would you like to stutter? 你想用什么词来口吃?
>> abcdefg >> abcdefg
>> aabbccddeeffgg >> aabbccddeegggg

Explanation: 说明:

What will happen when you try to s.charAt(0) when s is an empty String? s是空字符串时尝试s.charAt(0)会发生什么? You're not verifying that s is not empty, adding the simple check s.length() > 0 is what you're missing. 你没有验证s不是空的,添加简单的检查s.length() > 0就是你所缺少的。

Tip: Always use the debugger, it's there to help you, you'll better understand the flow of your program when you use it. 提示:始终使用调试器,它可以帮助您,您可以在使用它时更好地理解程序的流程。 Also when writing a recursion, using a pencil and a paper to draw the calls will help you to understand it. 此外,在编写递归时,使用铅笔和纸张绘制调用将有助于您理解它。

I did it like this: 我是这样做的:

My base case is when the length of the string is less than 1, in which case it will return "". 我的基本情况是当字符串的长度小于1时,在这种情况下它将返回“”。

Otherwise it will print of the first character of the string twice, and then call the stutter method again. 否则,它将打印字符串的第一个字符两次,然后再次调用stutter方法。

I pass in the original string as a parameter, except I have removed the first character from it.In this way the 2nd character of the original string will be printed out twice next and the string gets shorter. 我传入原始字符串作为参数,除了我已经从中删除了第一个字符。这样,原始字符串的第二个字符将在下一次打印出两次,字符串变短。

import java.util.*;

public class Stutter {  

    public static String stutter ( String s ) {
        if(s.length() < 1) return "";
        else{
            return "" + s.charAt(0) + s.charAt(0) + stutter(s.substring(1,s.length()));
        }
    }

    public static void main ( String [] args ) {
        Scanner s = new Scanner ( System.in );
        System.out.println ( "What word would you like to stutter?" );
        String userInput = s.nextLine();
        System.out.println(stutter(userInput));
    }
}

提示:如果s.length()为零,则s.charAt(0)将抛出异常...因为您正在尝试获取超出零长度字符串末尾的字符。

Check the length of your s variable before s.charAt (0) . s.charAt (0)之前检查s变量的长度。 For example, move 例如,移动

char ch = s.charAt (0);
String tempString = String.valueOf ( ch );

to else block 否则阻止

How about this: 这个怎么样:

public class Stutter {
    private static String head(String str) {
        return str.substring(0,1);
    }

    private static String tail(String str) {
        return str.substring(1);
    }

    private static String stutter(String str) {
        if (str.length() > 0)
            return head(str)+head(str)+stutter(tail(str));
        else
            return "";
    }

    public static void main(String args[]) throws Exception  {
        if (args.length > 0) {
            System.out.println(stutter(args[0]));
        }
    }
}

This can be achieved very simply using String.replaceAll() : 这可以使用String.replaceAll()非常简单地实现:

public class Stutter {
    public static void main (String args[]) {
        String TEST_STRING = "abcdefg";
        System.out.println(stutter(TEST_STRING));
    }

    private static String stutter(String s) {
        return s.replaceAll("(.)", "$1$1");
    }
}

Editted. Editted。

import java.util.*;

public class Stutter {

    static String stutterString = "";

    public static String stutter ( String s ) {
        if(s.length() > 0)
        {
            return stutterString.concat(s.substring(0,1)).concat(s.substring(0,1)).concat(stutter(s.substring(1)));
        }
        else
        {
            return stutterString;
        }
    }

    public static void main ( String [] args ) {


        Scanner inputScanner = new Scanner ( System.in );

        System.out.println ( "What word would you like to stutter?" );
        String userInput = inputScanner.next();

        inputScanner.close();

        System.out.println ( stutter ( userInput ) );

    }

}

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

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