英文:
Java split line from text file based on length and putting it into a vector
问题
首先,我对Java还不太熟悉,所以如果这个问题听起来很愚蠢,请原谅。为了解释我的程序,我需要创建一个二维向量,用于存储从文本文件中检索到的信息。所以假设我有一个像这样的文本文件:
12345 abcde 09876 mnbvc
8762121 hsggkqe 87201 hayib
5142 ayega 61 hsgwq
每一列的长度是固定的。我知道我们可以使用字符串分词器(String Tokenizer)在Java中拆分字符串,但在这种情况下,我们有多个“ ”(空格)。所以我的问题是,Java是否有类似于字符串分词器的东西,但是根据长度来分割字符串。这个方法是否可以做类似于 >9 和 <15 这样的操作,以获取中间的值?
英文:
First of all, I'm fairly new to Java so forgive me if this question sounds stupid. To explain my program, I need to create a 2d vector that stores information retrieved from a text file. So let's say I have a text file like this:
12345 abcde 09876 mnbvc
8762121 hsggkqe 87201 hayib
5142 ayega 61 hsgwq
Every column has a fixed length. I know we can split string in java by using String Tokenizer but in this case we have more than one " ". So my question is does Java has something similar to String Tokenizer but for splitting string based on length. Is it possible for the method to do something like >9 and <15 to get the value in the middle?
答案1
得分: 0
忘记列宽;根据任意数量的空格进行分割:
String[] columns = line.trim().split(" +");
split()
方法以正则表达式作为参数,而 " +"
表示“一个或多个空格”。
你需要调用 trim()
来去除前导空格,否则第一个返回的元素会是一个空字符串。
英文:
Forget column widths; split on any number of spaces:
String[] columns = line.trim().split(" +");
split()
takes a regular expression as its parameter, and " +"
means "one or more spaces".
You need the call to trim()
to strip off the leading spaces, otherwise you'd get a blank string as the first element returned.
答案2
得分: -1
Substrings应该能解决问题。子字符串允许你从一个起始索引获取一部分内容到一个结束索引(不包括结束索引本身)。
String substring(int beginIndex, int endIndex)
示例
假设lineOneText
代表你的文件的第一行文本。
String firstColumn = lineOneText.substring(0, 9) // 这将得到“ 12345”
String secondColumn = lineOneText.substring(9, 15) // 这将得到“ abcde”
英文:
Substrings should do the trick. Substrings give you a portion of the from a beginning index to an end index -1.
String substring(int beginIndex, int endIndex)
Example
Say lineOneText
represents the text from the first line of your file.
String firstColumn = lineOneText.substring(0, 9) // this equals " 12345"
String secondColumn = lineOneText.substring(9, 15) // this equals " abcde"
答案3
得分: -1
split方法将行使用split(" ")
方法进行分割,然后我们得到一个字符串数组,然后迭代字符串数组,找到非空字符串,代码可能如下所示:
String line = "12345 abcde 09876 mnbvc";
String[] words = line.split(" ");
List<String> list = new ArrayList<>(4);
for (String word : words) {
if (!word.isEmpty()) {
list.add(word);
}
}
System.out.println(list);
英文:
split the line use method split(" ")
and we get a String array,then iterate the String array find the not empty string,code may be like this:
String line = "12345 abcde 09876 mnbvc";
String[] words = line.split(" ");
List<String> list = new ArrayList<>(4);
for (String word : words) {
if (!word.isEmpty()) {
list.add(word);
}
}
System.out.println(list);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论