在用户输入的字符串之间添加 space

Adding a space inbetween a user inputed string

我希望用户输入一个字符串,然后以选定的间隔在字符之间添加一个 space。

示例:用户输入:你好 然后每 2 个字母要求一个 space。 输出 = he_ll_o_

import java.util.Scanner;

public class Whosebug {


    public static void main(String[] args) {


        System.out.println("enter a string");
        Scanner input = new Scanner(System.in);
        String getInput = input.nextLine();

        System.out.println("how many spaces would you like?");
        Scanner space = new Scanner(System.in);
        int getSpace = space.nextInt();


        String toInput2 = new String();

        for(int i = 0; getInput.length() > i; i++){

        if(getSpace == 0) {
            toInput2 = toInput2 + getInput.charAt(i);
            } 
        else if(i % getSpace == 0) {
            toInput2 = toInput2 + getInput.charAt(i) + "_"; //this line im having trouble with.
            }

        }


        System.out.println(toInput2);

    }



}

到目前为止,这就是我的代码,它可能是完全错误的解决方法,所以如果我错了请纠正我。提前致谢:)

我想你会想按如下方式制定你的循环体:

for(int i = 0; getInput.length() > i; i++) {
    if (i != 0 && i % getSpace == 0)
        toInput2 = toInput2 + "_";

    toInput2 = toInput2 + getInput.charAt(i);
}

但是,有一个更简单的方法,使用正则表达式:

"helloworld".replaceAll(".{3}", "[=11=]_")  // "hel_low_orl_d"

您可以将大小写区分简化为:

toInput2 += getInput.charAt(i);
if(i != 0 && i % getSpace == 0) {
    toInput2 += "_";
}

您还应该考虑重命名变量。