2015-03-31 126 views
2

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

示例:用户输入:你好 然后每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); 

    } 



} 

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

+0

将getInput命名为getInput并不是一个好主意,因为前缀get是按照惯例为getter和setter方法保留的。请参阅http://stackoverflow.com/questions/1568091/why-use-getters-and-setters一般来说,使用动词的变量名称是不常见的...... – Robert 2015-03-31 08:33:17

+0

,并且您的示例或描述是错误的,因为您添加了一个'你好''o'后面的空格... – Robert 2015-03-31 08:39:25

+0

好吧,如果没有下划线和空白,这就是即时通讯做的事情,如果在o后面有一个空格,这无关紧要。这只是一个例子,不能不在意我的变量名称是什么。 @Robert TY虽然:) – BriannaXD 2015-03-31 09:05:48

回答

4

我想你会想制定你的循环体,如下所示:

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" 
+0

谢谢,这有助于很多!也只是想知道,但在这一行“toInput2 = toInput2 + getInput.charAt(i);”只有当我!= 0 && i%getSpace == 0时才会添加一个字母?所以当它说charAt(i)它只会在charAt(i)加上字母,而不是字符串中的每个字母?我知道你说得很对,我很好奇。如果(i!= 0 && i%getSpace == 0) toInput2 = toInput2 +请参阅 – BriannaXD 2015-03-31 09:07:16

+0

oh不要担心,只是意识到这是为(int i = 0; getInput.length()> i; i ++){ “_”; toInput2 = toInput2 + getInput.charAt(i);如果(i!= 0 && i%getSpace == 0){ } toInput2 = toInput2 +“_”;如果(int i = 0; getInput.length()> i; i ++){ } } toInput2 = toInput2 + getInput.charAt(i); }大声笑,对不起我浪费你的时间 – BriannaXD 2015-03-31 09:20:58

0

可以简化您的情况区分为:

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

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

+1

这将始终在第一个字符后面插入一个“_”。 – aioobe 2015-03-31 08:35:42

+0

然后包括一个额外的检查...'我!= 0 && getSpace == 0' – Seb 2015-03-31 08:43:55

+0

哦这只是我的代码的一个例子。这些arnt我的实际变量名称。感谢您的帮助,虽然:) – BriannaXD 2015-03-31 08:56:16

相关问题