将从 .txt 文件读取的字符串输入到数组中

A. 价格

我正在为我的高中软件项目制作一个类似于应用程序的抽认卡。我可以通过将单词和它们各自的翻译写入文件来存储它们,但我想知道是否有可能将它们读入二维数组。

我可以用逗号或其他字符将它们分开吗?

此外,是否有一种方法可以将单词及其各自的翻译联系起来。例如,如果我调用单词“x”,是否有函数可以调用单词“translated x”(如果它在数组中)?

谢谢堆!!

马特

让我们把问题分解一下。

  • 读取文件
  • 解析文件中的每一行以确定 aword和 atranslation
  • word存储translation在数据结构中(@Glen Pierce 关于使用地图的建议是一个很好的建议)

假设我们的文件是这样的,我们使用逗号分隔单词和翻译(这也是我的西班牙语词汇量的范围):

hello,hola
good,bueno

现在一些代码,让我们将文件读入地图。

// a map of word to translation
Map<String, String> wordMap = new HashMap<String, String>();

// a class that can read a file (we wrap the file reader in a buffered reader because it's more efficient to read a file in chunks larger than a single character)
BufferedReader fileReader = new BufferedReader(new FileReader("my-file.txt"));

// a line from the file
String line;

// read lines until we read a line that is null (i.e. no more lines)
while((line = fileReader.getLine()) != null) {
    // split the line, returns an array of parts
    String[] parts = line.split(",");

    // store the parts in meaningful variables
    String word = parts[0];
    String translation = parts[1];

    // now, store the word and the translation in the word map
    wordMap.put(word, translation);
}

// close the reader (note: you should do this with a try/finally block so that if you throw an exception, you still close the reader)
fileReader.close();

所以现在我们有一个地图,其中包含文件中的所有单词和翻译。给定一个词,您可以像这样检索翻译:

String word = "hello";
String translation = wordMap.get(word);
System.out.println(word + " translates to " + translation);

输出:

hello translates to hola

我想下一步是让用户给你一个词,让你返回正确的翻译。我会把它留给你。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++从txt文件中读取getline并存储到字符串数组中

将从文件读取的字符串转换为 JSONObject android

无法将从文件读取的字符串与Java字符串进行比较

将从文本文件加载的字符串转换为JavaScript中的数组对象

从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”中读取的两行写入新文件“file2.txt”

如何在Java中逐行读取txt文件到字符串?

从原始txt文件中读取字符串

将从文本文件读取的字符串解析为整数

将从二进制文件读取的字符串转换为整数

如何比较输入与txt文件存储在数组中的字符串

如何在扫描仪输入中读取带有斜线“ /”的txt文件并将其放入数组/字符串中

如何将从文件中读取的值复制到数组列表中

列出将从 requirements.txt 安装的 Python 包

如何将从文件读取的数据存储到2D数组中

从txt文件中删除字符串数组单词

用文件 txt 中的单词填充字符串数组

如何从txt文件读取更改输入字符串输入格式

python:从.txt中读取并判断txt文件中的新字符串

从txt文件中删除字符串

如何读取将从.Net Core API中的表单上载的文件?

将从URL输出的JSON保存到文件

如何将从SQL读取的字符串逐字处理?

如何将从键盘读取的字符串传递给isdecimal等函数?

Java:如何将txt文件读取为字符串数组

Java如何读取txt文件并使每一行成为自己的字符串数组

从.txt文件中读取数字并替换.tex文件中的字符串

将从方法的实际值中返回

如何将从数据库检索到的int转换为字符串

如何使用c字符串读取.txt文件?