gpt4 book ai didi

java - 使用关键字将字符串拆分为多个部分

转载 作者:行者123 更新时间:2023-11-30 03:25:59 33 4
gpt4 key购买 nike

我有一个从 .txt 文件中读取的字符串,其中的值位于分隔的部分中

Text first 
[section_name_1]
Text with values pattern1
...
[section_name_2]
Text with values pattern2

我需要在 section_name_# 标记处拆分部分,并将它们添加到 String [] (数组的大小是固定的)。我的代码现在不会产生一些奇怪的输出:

//Code:
public static String[] parseFileToParams(File file)
{
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String[] params = new String[sections.length+1];
StringBuilder sb = new StringBuilder();
String decoded = parseFile(file);// Returns the Text from the file
for(int i=0; i< sections.length;i++)
{
params[i]= decoded.split(sections[i])[1];
sb.append(params[i]);
}
return params;
}
//For Test of the output
String[] textArray = BasicOsuParser.parseFileToParams(parseFile);
for(int j = 0; j<textArray.length;j++)
{
sb.append(textArray[j]);
}
String text= sb.toString();
System.out.println (text); //Output: su f form formau fnull
// Obviously not how it should look like

感谢您的帮助!

最佳答案

试试这个:

String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String textFromFile = "Text first [section_name_1] Text with values pattern1 [section_name_2] Text with values pattern2";
int count = 0;
for(int i = 0; i < sections.length; i++){
if(textFromFile.contains(sections[i])){//Use this to tell how big the parms array will be.
count++;
}
sections[i] = sections[i].replace("[", "\\[").replace("]", "\\]");//Removes the brackets from being delimiters.
}
String[] parms = new String[count+1];//Where the split items will go.
int next = 0;//The next index for the parms array.
for(String sec : sections){
String split[] = textFromFile.split(sec);//Split the file's text by the sec
if(split.length == 2){
parms[next] = split[0];//Adds split to the parms
next++;//Go to the next index for the parms.
textFromFile = split[1];//Remove text which has just been added to the parms.
}
}
parms[next] = textFromFile;//Add any text after the last split.
for(String out : parms){
System.out.println(out);//Output parms.
}

这将执行您所要求的操作,并对其进行了注释,以便您可以了解它是如何工作的。

关于java - 使用关键字将字符串拆分为多个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198771/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com