suprapto45
asked on
Splitting String Efficiency
Hi,
The scenario is that I want to split the string into 10 chars length each. do you think that the below codes are efficient as String is immutable? If not, can you let me know how to improve below codes?
String a = "12345667788";
StringBuffer sb = new StringBuffer();
sb.append(a);
int part = 1;
while (sb.length() > 0) {
System.out.println("Enteri ng " + part);
String temp = sb.substring(0, sb.length() >= 10 ? 10 : sb.length());
sb.delete(0, sb.length() >= 10 ? 10 : sb.length());
System.out.println("temp = " + temp);
part++;
}
sb = null;
Thanks
David
The scenario is that I want to split the string into 10 chars length each. do you think that the below codes are efficient as String is immutable? If not, can you let me know how to improve below codes?
String a = "12345667788";
StringBuffer sb = new StringBuffer();
sb.append(a);
int part = 1;
while (sb.length() > 0) {
System.out.println("Enteri
String temp = sb.substring(0, sb.length() >= 10 ? 10 : sb.length());
sb.delete(0, sb.length() >= 10 ? 10 : sb.length());
System.out.println("temp = " + temp);
part++;
}
sb = null;
Thanks
David
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Oppsss...
I think that I know what you mean.
Do you mean this? If so, yes it is much cleaner and better I think.
String a = "12345667788";
StringBuffer sb = new StringBuffer();
sb.append(a);
int part = 1;
int pos = 0;
while (pos < sb.length()) {
System.out.println("Enteri ng " + part);
String temp = sb.substring(pos, Math.min(pos+10, sb.length()));
System.out.println("temp = " + temp);
pos += 10;
part++;
}
sb = null;
Thanks
David
I think that I know what you mean.
Do you mean this? If so, yes it is much cleaner and better I think.
String a = "12345667788";
StringBuffer sb = new StringBuffer();
sb.append(a);
int part = 1;
int pos = 0;
while (pos < sb.length()) {
System.out.println("Enteri
String temp = sb.substring(pos, Math.min(pos+10, sb.length()));
System.out.println("temp = " + temp);
pos += 10;
part++;
}
sb = null;
Thanks
David
substring() returns a new string, it doesn't modify the original one
ASKER
Thanks mate
ASKER
But I thought that String is immutable and that is the reason why I used StringBuffer. Or am I missing some concepts here? ;)
Thanks
David