I can iterate through the alphabet, but I'm trying to keep the last iteration and add on the next letter. this is my code.
for(char alphabet = 'a'; alphabet <='z'; alphabet ++ )
{
System.out.println(alphabet);
}
I want it to print out something that looks like this.
a
ab
abc
abcd
abcde..... and so forth. How is this possible?
I'd suggest using a StringBuilder
:
// Using StringBuilder
StringBuilder buf = new StringBuilder();
for (char c = 'a'; c <= 'z'; c++)
System.out.println(buf.append(c).toString());
You could also do it slightly faster by using a char[]
, however StringBuilder
is more obvious and easier to use:
// Using char[]
char[] arr = new char[26];
for (int i = 0; i < 26; i++) {
arr[i] = (char)('a' + i);
System.out.println(new String(arr, 0, i + 1));
}
Alternatives that you shouldn't use:
StringBuffer
: Same as StringBuilder
, but synchronized, so slower.s = s.concat(new String(c))
: Allocates 2 Strings per iteration, instead of only 1.s += c
: Internally +=
is compiled to s = new StringBuilder().append(s).append(c).toString()
, so horrendously slow with exponential response times.You need to add the char alphabet
to a string.
String output = "";
for(char alphabet = 'a'; alphabet <='z'; alphabet++ )
{
output += alphabet;
System.out.println(output);
}
This should work for you ;)
I will go with StringBuffer or StringBuilder. Something like:
StringBuffer
StringBuffer sb = new StringBuffer();
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
sb.append(alphabet);
System.out.println(sb.toString());
}
StringBuilder
StringBuilder sb = new StringBuilder();
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
sb.append(alphabet);
System.out.println(sb.toString());
}
String vs StringBuffer vs StringBuilder:
String: It is immutable, so when you do any modification in the string, it will create new instance and will eatup memory too fast.
StringBuffer: You can use it to create dynamic String and at the sametime only 1 object will be there so very less memory will be used. It is synchronized (which makes it slower).
StringBuilder: It is similar to StringBuffer. The olny difference is: it not synchronized and hence faster.
So, better choice would be StringBuilder. Read more.
Using Java 8
StringBuilder sb = new StringBuilder();
IntStream.range('a', 'z').forEach(i -> {
sb.append((char) i);
System.out.println(sb.toString());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With