gpt4 book ai didi

java - 如何在单词中间添加空格

转载 作者:行者123 更新时间:2023-12-01 13:48:20 26 4
gpt4 key购买 nike

大家好,在单词之间添加空格时遇到问题。我需要做的是将英语转换为 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​​//新短语

最佳答案

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

关于java - 如何在单词中间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20172466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com