Link to home
Start Free TrialLog in
Avatar of suprapto45
suprapto45Flag for Singapore

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("Entering " + 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
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of suprapto45

ASKER

Thanks,

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
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("Entering " + part);
                  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
Thanks mate