【发布时间】:2016-06-10 05:47:43
【问题描述】:
试图从 coderbyte 完成这个挑战:“使用 Java 语言,让函数 LetterChanges(str) 获取传递的 str 参数并使用以下算法对其进行修改。将字符串中的每个字母替换为它后面的字母字母表(即 c 变为 d,z 变为 a)。然后将这个新字符串中的每个元音大写(a,e,i,o,u),最后返回这个修改后的字符串。"
我遇到的问题是替换是拉动字符之间的空格,但我需要它来保留单词之间的空格。有没有更好的解决方案?
import java.util.Arrays;
import java.util.Scanner;
public class nextLetter {
public static String LetterChanges(String str) {
String[] inputString = str.replaceAll("[^a-zA-Z ]", "").split("");
String[] alph= "abcdefghijklmnopqrstuvwxyz".split("");
String[] vowel ="aeiouy".split("");
for(int i=0; i<inputString.length; i++){
int index= Arrays.asList(alph).indexOf(inputString[i])+1;
inputString[i]= alph[index];
if(Arrays.asList(vowel).indexOf(inputString[i])>0){
inputString[i]= inputString[i].toUpperCase();
}
}
//System.out.println(Arrays.toString(inputString));
return Arrays.toString(inputString)
.replace(" ","")
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")//remove the left bracket
.replace(" ","")
.trim();
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter a sentence");
System.out.print(LetterChanges(s.nextLine()));
}
}
我也不介意任何关于如何改进这一点的建议!
【问题讨论】:
-
那么,你的问题到底是什么?
-
当我输入“测试句”时,输出是 UftUatfOUfOdf,当它仍然应该是 2 个单独的“单词”时
-
您正在删除所有的空白。如果您想保留它,请不要删除它。无论如何,@Michael 有更好的方法。
-
通过代码的演练更新了我的答案
标签: java arrays arraylist replace