【问题标题】:Adding a space inbetween a user inputed string在用户输入的字符串之间添加空格
【发布时间】:2015-06-04 12:13:27
【问题描述】:

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

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

import java.util.Scanner;

public class stackOverflow {


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

    }



}

到目前为止,这是我的代码,它可能是完全错误的解决方法,如果我错了,请纠正我。在此先感谢:)

【问题讨论】:

  • 将字符串命名为getInput 不是一个好主意,因为前缀get 是为getter 和setter 方法保留的约定。见stackoverflow.com/questions/1568091/why-use-getters-and-setters 一般情况下,变量名不使用动词...
  • 你的例子或者你的描述是错误的,因为你在helloo之后添加了一个空格...
  • 好吧,如果没有下划线而只有空格,这就是我正在做的事情,如果 o 后面有空格也没关系。这只是一个例子,不在乎我的变量名是什么。 @Robert ty 虽然:)

标签: java string java.util.scanner whitespace


【解决方案1】:

您可以将案例区分简化为:

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

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

【讨论】:

  • 这将始终在第一个字符后插入_
  • 然后包括一个额外的检查...i != 0 && getSpace == 0
  • 哦,这只是我的代码示例。这些不是我的实际变量名。不过感谢您的帮助:)
【解决方案2】:

我想你会想要如下制定你的循环体:

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

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

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

"helloworld".replaceAll(".{3}", "$0_")  // "hel_low_orl_d"

【讨论】:

  • 谢谢,这帮助很大!也只是想知道,但在这一行“toInput2 = toInput2 + getInput.charAt(i);”不会只在 i != 0 && i % getSpace == 0 时添加一个字母吗?所以当它说 charAt(i) 时,它只会在 charAt(i) 处添加字母,而不是字符串中的每个字母?我知道你是对的,我是错的,我只是好奇。再次感谢大家
  • 哦别担心,刚刚意识到这是 for(int i = 0; getInput.length() > i; i++) { if (i != 0 && i % getSpace == 0) toInput2 = toInput2 + ""; toInput2 = toInput2 + getInput.charAt(i); } 等同于 for(int i = 0; getInput.length() > i; i++) { if (i != 0 && i % getSpace == 0){ toInput2 = toInput2 + ""; } toInput2 = toInput2 + getInput.charAt(i); } 大声笑,对不起,我浪费了你的时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多