嘿伙计们在单词之间添加空格时遇到了麻烦。我需要做的是将英语转换为我已经完成的Vogon,但你还必须在5个字符中添加空格任何想法如何做到这一点就是我的代码。
public static void main(String[] args) {
translateFromEnglish("hello");
}
public static boolean detect(String phrase) {
return false;
}
public static String translateFromEnglish(String phrase){
Scanner scan = new Scanner(System.in);
phrase = scan.nextLine();
String NewString = "";
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == 'a') {
NewString += "n";
}
if (phrase.charAt(i) == 'b') {
NewString += "o";
}
if (phrase.charAt(i) == 'c') {
NewString += "p";
}
if (phrase.charAt(i) == 'd') {
NewString += "q";
}
if (phrase.charAt(i) == 'e') {
NewString += "r";
}
if (phrase.charAt(i) == 'f') {
NewString += "s";
}
if (phrase.charAt(i) == 'g') {
NewString += "t";
}
if (phrase.charAt(i) == 'h') {
NewString += "u";
}
if (phrase.charAt(i) == 'i') {
NewString += "v";
}
if (phrase.charAt(i) == 'j') {
NewString += "w";
}
if (phrase.charAt(i) == 'k') {
NewString += "x";
}
if (phrase.charAt(i) == 'l') {
NewString += "y";
}
if (phrase.charAt(i) == 'm') {
NewString += "z";
}
if (phrase.charAt(i) == 'n') {
NewString += "a";
}
if (phrase.charAt(i) == 'o') {
NewString += "b";
}
if (phrase.charAt(i) == 'p') {
NewString += "c";
}
if (phrase.charAt(i) == 'q') {
NewString += "d";
}
if (phrase.charAt(i) == 'r') {
NewString += "e";
}
if (phrase.charAt(i) == 's') {
NewString += "f";
}
if (phrase.charAt(i) == 't') {
NewString += "g";
}
if (phrase.charAt(i) == 'u') {
NewString += "h";
}
if (phrase.charAt(i) == 'v') {
NewString += "i";
}
if (phrase.charAt(i) == 'w') {
NewString += "j";
}
if (phrase.charAt(i) == 'x') {
NewString += "k";
}
if (phrase.charAt(i) == 'y') {
NewString += "l";
}
if (phrase.charAt(i) == 'z') {
NewString += "m";
}
}
System.out.println(NewString);
return phrase;
}
控制台 你好,你是如何做//用户输入的 uryybubjnerlbhqbvat //新短语
答案 0 :(得分:1)
使用StringBuilder更有效,因为您不需要每次都创建一个字符串:
String translatedString = "aaaaabbbbbeeeeecccccdddddfffffgggg";
int numOfChars = 5;
StringBuilder vogon = new StringBuilder();
for (int i = 0; i < (translatedString.length() / numOfChars); i++) {
vogon.append(translatedString.substring(i * numOfChars, (i * numOfChars) + 5)).append(" ");
}
// append any remaining characters
vogon.append(" ").append(translatedString.substring(translatedString.length()/numOfChars));
System.out.println(vogon);
答案 1 :(得分:0)
要在for
循环中找到第五个字符并添加字符串,您可以包含以下简单内容:
if (i % 5 == 0){
newString += " ";
}
答案 2 :(得分:0)
维护一个计数器并在for循环中递增它。在所有if语句结束时
count++;
if(count % 5 == 0){
NewString += " ";
}