1

I have a very long String and I want to read character by character until the end of the String.

In Java, I found two ways to read it:

  1. Using CharAt.
  2. Using StringReader.

Can anybody help me:

  1. Which one is the faster way ?
  2. How to use StringReader to read character by character until the end of the String ?

Thanks in advance.

Arpssss
  • 3,850
  • 6
  • 36
  • 80

4 Answers4

3
  1. Measure it and find out! Seriously, things may be different for me on my hardware compared to you on your hardware. But I suspect charAt()
  2. It's just a Reader, so it has the same methods as any other Reader, including int read() which will return you the Unicode code point for each character, one by one
dty
  • 18,795
  • 6
  • 56
  • 82
2
  1. Measure it yourself. I can't see there being a meaningful/significant difference, once the string is loaded into memory.
  2. StringReader#read() (RFTD)
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2

How long is "very long?"

Convert the string to a char array using the toCharArray() method and have at it from a loop:

String mystring = "test";

char[] myCharArray = mystring.toCharArray();

  • That doesn't answer either question the OP asked. – Matt Ball Mar 21 '12 at 17:34
  • 1
    He wants to "read character by character until the end of the string." –  Mar 21 '12 at 17:36
  • And then he says that in Java he found two ways to read it and I am offering him a third way that might work. –  Mar 21 '12 at 17:58
  • In case you need more convincing that I'm not trolling: http://stackoverflow.com/questions/1672415/charat-or-substring-which-is-faster –  Mar 21 '12 at 18:44
1

Here is a simple class designed to do as you requested, with a charAt method:

public class Test {

static String tS = "Hello this is a string";


public static void main (String args []) {
//make a blank character that gets replaced each time the for loop runs     
char c;     
    for (int j = 0; j < tS.length(); j++) {
            //for loop runs up the length of the string, then sets c to the
            //current character in the string. Printing c just proves the concept.
        c = tS.charAt(j);
        System.out.println(c);
    }
}
}

Please remember that none of this needs to be done in a class or a main method - you could do it anywhere within your code that you needed it.

Davek804
  • 2,804
  • 4
  • 26
  • 55