0

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.

catch23
  • 17,519
  • 42
  • 144
  • 217
BelieveToLive
  • 281
  • 1
  • 4
  • 18

4 Answers4

2

There is method in string toCharArray()

"aab".toCharArray()

But this method anyway requires additional memory for new char array

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Natalia
  • 4,362
  • 24
  • 25
1

Is there a reason why you want to store all the characters of the string in an array? If you just want to print the characters one by one, there's no need to store them in an array.

Your for loop line also contains errors.

String x = "<BigBus><color>RED</color><number>123</number>........</BigBus>";

for(int i=0; i < x.length(); i++) {
    char c = x.charAt(i);
    System.out.println(c);
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
1
xh = x.toCharArray();

This'll solve the issue

1

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]);
}
catch23
  • 17,519
  • 42
  • 144
  • 217