dicle :
I have a txt file that includes :
Hello Word
myStrings = [str1, str2, str3]
Goodbye Word
I would like to read the file to find the "myStrings" string then have a loop to check if one of the myStrings value [str1, str2, str3] match with a some variable.
Currently I am finding the myStrings like this:
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
String myStringsKey = "myStrings =";
if(fileline.startsWith(myStringsKey)) {
}
}
How can I achieve str2 for instance to check with a defined var? I assume I should use "split".
zappee :
For parsing your string you can use the following simple method:
public String[] parseMyStrings(String s) {
int beginIndex = s.indexOf("[") + 1;
int endIndex = s.indexOf("]");
s = s.substring(beginIndex, endIndex);
// split and trim in one shot
return s.split(("\\s*,\\s*"));
}
Then, your final code can look like this:
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
String myStringsKey = "myStrings =";
if(fileline.startsWith(myStringsKey)) {
String[] values = parseMyStrings(fileline);
System.out.println(Arrays.toString(values));
}
}
I think your code will be more readable and easier to extend or modify if you put the parsing logic into a separate method.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=329375&siteId=1