对所有编码员都很高兴,任何帮助都表示赞赏,因为这是一个个人项目,而不是我认为会很有趣的学校,但事实并非如此。现在该项目是读入一个输入文件,将其与srting [] alphabets = {“a”,“b”,“c”......“z”}进行比较,然后用另一个字符串替换字母[ ] newAlphabets = {“Apple”,“Ball”,“Cat”,......“Zebra”}。现在我尝试了简单的replaceAll()示例,它有点工作。但计划是输入.txt文件并使用新文件进行替换运行和输出。 JamesBond.txt :姓名是邦德,詹姆斯邦德。 Output.txt 应为:NoAppleMonkeyElephant InsectSnake BallOpenNoDuck,JungelAppleMonkeyElephantSnake BallOpenNoDuck。 这是我到目前为止所拥有的:
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class FnR {
// array of alphabets
static String[] alphabet = {"a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"};
// replace the alphabets with substituted string
static String[] newAlphabets =
{"Apple","Bat","Cat","Dog","Egale","Fox","Goat","Horse","Insect","Jungle",
"King","Lion","Monkey","Nose","Open","Push","Quit","Run","Stop","Turn",
"Up","Volume","Water","X-mas","Yes","Zip"};
@SuppressWarnings("resource")
public static void main(String[] arg) throws IOException{
try {
//reads in the file
Scanner input = new Scanner("JamesBond.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
//prints the txt file out
System.out.println(line);
// replaces the letter j with Jungel in the text regardless of
case
String newtxt1 = line.replaceAll("J","Jungle");
//prints new text
System.out.println(newtxt1);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} }
Output:
Name is Bond, James Bond
Name is Bond, Jungleames Bond
答案 0 :(得分:1)
不会给你代码。这个答案为您提供了自己编写代码的提示。
不要使用replaceAll()
。你必须做26次,这不是一个好的解决方案。
而是创建一个StringBuilder
来构建结果字符串。然后使用String方法length()
和charAt()
以正常for
循环遍历输入字符串的字符。
现在这里是主要的"技巧"这将简化您的代码。 Java以Unicode格式存储文本,其中连续存储字母a
到z
。这意味着您可以计算索引到newAlphabets
数组中。为此,您将编写如下代码:
char ch = ...;
if (ch >= 'a' && ch <= 'z') {
int idx = ch - 'a'; // number between 0 and 25, inclusive
// use idx here
} else if (ch >= 'A' && ch <= 'Z') {
int idx = ch - 'A'; // number between 0 and 25, inclusive
// use idx here
} else {
// not a letter
}
希望这可以帮助您自己编写代码。