Search code examples
javastringchars

What is the best and effective way to read chars from string in java


I want to know the effective way of reading a string which does not affect memory nor performance of the program.

I have the following implementation:

String x = "<BigBus><color>RED</color><number>123</number>........</BigBus>";
    char[] xh = new char[x.length()];
    for(int i=0;x.length();i+) {
       ch[i]=x.charAt(i);
       System.out.println(ch[i]);
    }

The sample string larger and have multiple lines.


Solution

  • The best solution will be to use Java 8 features for this.

    Method chars() returns chars from given string. But it prints just char number value. For convenience we have to add utility method:

    public class IterateString {
    
        private static void printChar(int aChar) {
            System.out.println((char) (aChar));
        }
    
        public static void main(String[] args) {
            String str = "<BigBus><color>RED</color><number>123</number>........</BigBus>";
    
            str.chars()
                    .forEach(IterateString::printChar);
    
            // other options
            System.out.println();
            str.chars()
                .mapToObj(ch -> (char) ch)
                .forEach(System.out::println);
    
            System.out.println();
            str.chars()
                .filter(Character::isDigit)
                .forEach(IterateString::printChar);
        }
    }
    

    With streams you have a lot of benefits as lazy evaluation, lambda syntax, method references... For more info follow java 8 features.

    BTW
    your code snippet has some mistakes, it should look as follows:

        for (int i = 0; i < str.length(); i++) {
            ch[i] = str.charAt(i);
            System.out.println(ch[i]);
        }
    

    instead of:

    char[] xh = new char[x.length()];
    for(int i=0; x.length(); i+) {
       ch[i] = x.charAt(i);
       System.out.println(ch[i]);
    }