Solved

java challenge string builder

Posted on 2014-11-14
19
367 Views
Last Modified: 2014-12-05
Hi,

I am working on below coding challenge
http://codingbat.com/prob/p197720
i wrote as below


public String left2(String str) {
  StringBuilder sb1=new StringBuilder();
  StringBuilder sb2=new StringBuilder();
  StringBuilder sb3=new StringBuilder();
  String result=null;
   String str1=null;
    String str2=null;
  //for(int i=0;i<str.length();i++){
  if(str.length()>=2){
  str1=str.substring(0,2);
  str2=str.substring(2,str.length());
  
  result=str2+str1;
  }
  return result;
  
  
  
  
}

Open in new window


My test cases are passing.
i would like to know how can improve on my above code. How to use string builder in this case Please advise.Thanks in advance
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
  • 4
  • +1
19 Comments
 
LVL 16

Assisted Solution

by:krakatoa
krakatoa earned 167 total points
ID: 40442513
Again, all you really need here is :

public String left2(String str) {
        return str.substring(2,str.length())+str.substring(0,2);
}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 40442539
Much like you did in http:Q_28562068.html
0
 
LVL 32

Accepted Solution

by:
awking00 earned 166 total points
ID: 40444448
While a String object is immutable (i.e. can not be changed), a StringBuilder object is not and can easily be created from and converted to a String object. As such, its application can be very useful for the manipulation of Strings. Take a look at this code - only two lines to return the correct string
      public static String left2(String str) {
            //create StringBuilder object from str
            StringBuilder sb = new StringBuilder(str);
            //return a String starting with the third character
            //after adding first 2 characters to the end
            return sb.append(sb.substring(0, 2)).substring(2).toString();
      }
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 7

Author Comment

by:gudii9
ID: 40458895
While a String object is immutable (i.e. can not be changed), a StringBuilder object is not

I have not clearly understood this immutability. To me both below solutions seems same. Please advise which one to use in which case.

stringbuilder solution
      public static String left2(String str) {
            //create StringBuilder object from str
            StringBuilder sb = new StringBuilder(str);
            //return a String starting with the third character
            //after adding first 2 characters to the end
            return sb.append(sb.substring(0, 2)).substring(2).toString();
      }

Open in new window


string example
      public static String left2(String str) {
            //create StringBuilder object from str
            StringBuilder sb = new StringBuilder(str);
            //return a String starting with the third character
            //after adding first 2 characters to the end
            return sb.append(sb.substring(0, 2)).substring(2).toString();
      }

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 40458995
those are identical stringbuilder solutions
an equivalent string example might be
     public static String left2(String str) {
            return (str + str.substring(0, 2)).substring(2);
     }
0
 
LVL 32

Expert Comment

by:awking00
ID: 40459495
To help you understand the immutability of String objects vs. StringBuilder objects, look at the following two pieces of code that accomplish the same thing. I have broken the code down into intermediate steps so you can see how the String object does not change, but the StringBuilder object does.

String example (using ozo's example)

String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

StringBuilder example

String str = "abcde";
StringBuilder sb = new StringBuilder(str); ==> at this point sb.toString produces "abcde"
sb.append(str.substring(0,2); ==> at this point sb.toString produces "abcdeab" (i.e. sb has changed)
sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change
0
 
LVL 7

Author Comment

by:gudii9
ID: 40467787
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change
in case of string str did not change as above


in case of string builder it changed in every step on sb right without need of creating new object.

But i wonder how it printed "abcde" in last step as below



return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change




I thought it will print "cdeab"  as that is last operation on sb

sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
0
 
LVL 84

Expert Comment

by:ozo
ID: 40468372
sb has changed.
str has not changed.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40469807
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change

above is not clear to me. How the changed sb did not reflect in str when we did sb.toString

please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40469820
return sb.toString();
   uses sb, and does not mention str
   if it  was
str=sb.toString();
   then str could have been replaced
0
 
LVL 32

Expert Comment

by:awking00
ID: 40470364
>>above is not clear to me. How the changed sb did not reflect in str when we did sb.toString<<
I keep telling you a String object can NOT be changed. You can return sb.toString(), which is a new String, but you can not replace str with sb.toString() as it already has the value of "abcde" (or whatever is passed in as the String parameter) and always will.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40470415
String objects are immutable.  String references, however, are mutable.
Here, str is a reference and you can replace str with sb.toString().
0
 
LVL 32

Expert Comment

by:awking00
ID: 40470514
ozo,
I absolutely agree and shame on me for not recognizing that str is a reference in this case.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40470537
To help you understand the immutability of String objects vs. StringBuilder objects, look at the following two pieces of code that accomplish the same thing. I have broken the code down into intermediate steps so you can see how the String object does not change, but the StringBuilder object does.

String example (using ozo's example)

String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

StringBuilder example

String str = "abcde";
StringBuilder sb = new StringBuilder(str); ==> at this point sb.toString produces "abcde"
sb.append(str.substring(0,2); ==> at this point sb.toString produces "abcdeab" (i.e. sb has changed)
sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change

i am confused. Can you please make the necessary correction in above comment and re post so that i will read and re read to understand.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40470544
what is meaning of string references are mutable?
I think i got what it mean mean by strings are immutable based on below statements
String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

so basically to change/modify/append string object only way is to create new sting reference objects like str, newStrign, result etc.

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40472481
When you say
String newString = str + str.substring(0,2);
the result is a placed in a new String object which is designated as newString

When you say
str = str + str.substring(0,2);
the result placed in a newly created String object which then replaces the previous str

When you say
sb.append(str.substring(0,2);
the previously existing StringBuilder object is altered and no new object is created.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40472718
When it replaces the previous str then previous str still remains hanging there right.
When you say sb.append......then it should be assigned to other sb eight.
Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40482834
StringBuilder sb = new StringBuilder("abcd");

can you create string builder above as above? please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 167 total points
ID: 40482893
Yes you can, as you can discover by trying it.
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question