读取文件并拆分其内容并存储在数组中

时间:2021-08-26 06:09:29

I have this kind of file structure:

我有这种文件结构:

0 0:124 25:11  
1 0:36 12:1 

with the interpretation:

与解释:

<class> <array_index>:<class_occurrences> <array_index>:<class_occurrences> ...

All the missing array_index should be initialized to zeros.

所有缺少的array_index应该初始化为零。

I want to identify the class and store the class_occurrences in an array.

我想识别类并将class_occurrences存储在数组中。

So like I wanted to store class and its occurrences in a composite data structure(Array) class and its corresponding occurrences can be linked together say, line number in the file.

所以就像我想在复合数据结构(Array)类中存储类及其出现的那样,它的相应事件可以链接在一起说,文件中的行号。

1 个解决方案

#1


1  

You can split a string into an array with the .split() method

您可以使用.split()方法将字符串拆分为数组

Since each of your lines in the structure has 3 sections separated by a space, you can split the line into 3 parts with string.split(regex).

由于结构中的每一行都有3个由空格分隔的部分,因此可以使用string.split(正则表达式)将该行拆分为3个部分。

The regex can be a space, which will return an array of each 3 components, "0", "0:124" and "25:11".

正则表达式可以是一个空格,它将返回每个3个组件的数组,“0”,“0:124”和“25:11”。

You can then split those strings again by the colon symbol, but make sure that the string split into 3 components, otherwise you will get an ArrayIndexOutOfBoundsException if you try to access the 3rd component if it doesn't exist.

然后,您可以通过冒号符号再次拆分这些字符串,但请确保将字符串拆分为3个组件,否则如果您尝试访问第3个组件(如果它不存在),则会得到ArrayIndexOutOfBoundsException。

After you have all those individual numbers, you can parse them into integers, and you can name those variables such as class, array_index and class_occurrences.

拥有所有这些单独的数字后,您可以将它们解析为整数,并且可以命名这些变量,例如class,array_index和class_occurrences。

#1


1  

You can split a string into an array with the .split() method

您可以使用.split()方法将字符串拆分为数组

Since each of your lines in the structure has 3 sections separated by a space, you can split the line into 3 parts with string.split(regex).

由于结构中的每一行都有3个由空格分隔的部分,因此可以使用string.split(正则表达式)将该行拆分为3个部分。

The regex can be a space, which will return an array of each 3 components, "0", "0:124" and "25:11".

正则表达式可以是一个空格,它将返回每个3个组件的数组,“0”,“0:124”和“25:11”。

You can then split those strings again by the colon symbol, but make sure that the string split into 3 components, otherwise you will get an ArrayIndexOutOfBoundsException if you try to access the 3rd component if it doesn't exist.

然后,您可以通过冒号符号再次拆分这些字符串,但请确保将字符串拆分为3个组件,否则如果您尝试访问第3个组件(如果它不存在),则会得到ArrayIndexOutOfBoundsException。

After you have all those individual numbers, you can parse them into integers, and you can name those variables such as class, array_index and class_occurrences.

拥有所有这些单独的数字后,您可以将它们解析为整数,并且可以命名这些变量,例如class,array_index和class_occurrences。