Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- public class Test {
- private static class PathReader {
- private String inputString;
- private int currentPosition = 0;
- private int length = 0;
- public PathReader(String string) {
- inputString = string;
- length = inputString.length();
- currentPosition = 0;
- }
- public boolean hasNext() {
- skipSpaces();
- return currentPosition < length;
- }
- public char getNext() {
- return inputString.charAt(currentPosition++);
- }
- public char peekNext() {
- return inputString.charAt(currentPosition);
- }
- private void skipCharacter() {
- currentPosition++;
- }
- private void skipSpaces() {
- while (currentPosition < length) {
- char c = peekNext();
- switch (c) {
- case ' ':
- case ',':
- case '\n':
- case '\t':
- case '\r':
- break;
- default:
- return;
- }
- skipCharacter();
- }
- }
- public float parseFloat() {
- boolean exp = false;
- int j = currentPosition;
- if (inputString.charAt(j) == '-') {
- getNext();
- }
- while (currentPosition < length) {
- char c = getNext();
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '+':
- case '.':
- exp = false;
- break;
- case '-':
- if (exp) {
- exp = false;
- } else {
- currentPosition--;
- return Float.parseFloat(inputString.substring(j, currentPosition));
- }
- break;
- case 'e':
- case 'E':
- exp = true;
- break;
- default:
- currentPosition--;
- return Float.parseFloat(inputString.substring(j, currentPosition));
- }
- }
- return Float.parseFloat(inputString.substring(j, currentPosition));
- }
- }
- public static void main(String[] args) throws IOException {
- String data = new String(Files.readAllBytes(Paths.get("test.txt")), StandardCharsets.UTF_8);
- // TEST 1
- long time = System.nanoTime();
- for( int i = 1; i < 1000; i++ ){
- PathReader reader = new PathReader(data);
- while(reader.hasNext()){ reader.parseFloat(); }
- }
- time = System.nanoTime() - time;
- System.out.println("Using reader: " + time);
- // TEST 2
- time = System.nanoTime();
- for( int i = 1; i < 1000; i++ ){
- data.replaceAll("[^\\d.-]|(?=-)", " ").trim().split(" +");
- }
- time = System.nanoTime() - time;
- System.out.println("Using regexp: " + time);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement