Reputation: 21
Is there a built in method in Java to determine if a String starts with a specific character? How can I write, to an output file, only the lines that do not start with a defined character?
try {
File input = new File("input");
File output = new File("output");
Scanner sc = new Scanner(input);
PrintWriter printer = new PrintWriter(output);
while (sc.hasNextLine()) {
String s = sc.nextLine();
printer.write(s);
}
printer.flush();
}
catch (FileNotFoundException e) {
System.err.println("File not found. Please scan in new file.");
}
Upvotes: 2
Views: 4003
Reputation: 6132
Built in a check if the character is there.
while (sc.hasNextLine()) {
String s = sc.nextLine();
if (s.startsWith("?"))
printer.write(s);
}
Or
while (sc.hasNextLine()) {
String s = sc.nextLine();
char c = s.charAt(0);
if (c.matches('?'))
printer.write(s);
}
EDIT: Based on your comment:
int i;
char c;
String s;
while (sc.hasNextLine()) {
s = sc.nextLine();
c = ' ';
i = 0;
while (c.matches(' ')) {
c = s.charAt(i);
if (c.matches('?'))
printer.write(s);
i++;
}
}
Not sure if the code works, I'm currently unable to test the code. But you might get the idea.
Upvotes: 1
Reputation: 7940
You can easily check for text before writing in your while loop.
if(check your string)
printer.write(s);
Upvotes: 0