[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 138
  • Last Modified:

without x2 challenge

Hi,

I am trying below challenge
http://codingbat.com/prob/p151359
i tried like below
public String without2(String str) {
  int strLen=str.length();
  String strOut=str;
  
  if(strLen>=2 && str.substring(0,2).equals(str.substring(strLen-2))){
  
  strOut=str.substring(2,strLen);
  return strOut;
  }
   else{
  
 // strOut=str.substring(strLen-2);
  return strOut;
  }
  //return strOut;
}

Open in new window


i am failing tests as below
Expected	Run		
withoutX2("xHi") → "Hi"	"xHi"	X	    
withoutX2("Hxi") → "Hi"	"Hxi"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	"xxHi"	X	    
withoutX2("Hix") → "Hix"	"Hix"	OK	    
withoutX2("xaxb") → "axb"	"xaxb"	X	    
withoutX2("xx") → ""	"xx"	X	    
withoutX2("x") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:8)"	X	    
withoutX2("") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:6)"	X	    
withoutX2("Hello") → "Hello"	"Hello"	OK	    
withoutX2("Hexllo") → "Hexllo"	"Hexllo"	OK	    
withoutX2("xHxllo") → "Hxllo"	"xHxllo"	X	    
other tests

Open in new window


i wonder how to fix and improve my code. please advise
0
gudii9
Asked:
gudii9
  • 32
  • 24
  • 12
2 Solutions
 
ozoCommented:
It looks like you are trying to solve http://codingbat.com/prob/p142247
http://codingbat.com/prob/p151359 is different
0
 
gudii9Author Commented:
not getting ideas on this challenge too. please advise
0
 
ozoCommented:
Maybe start with simpler cases.  Can you solve it when only the first char is 'x'?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
zzynxSoftware engineerCommented:
Show us the code you wrote to solve http://codingbat.com/prob/p151359.
The code you posted is no attempt to solve http://codingbat.com/prob/p151359.
0
 
gudii9Author Commented:
public String withoutX2(String str) { 
  

int strLen=str.length();
String st=null;

if(str.substring(0,1).equals("x") & str.substring(1,2).equals("x"))
{
st=str.substring(strLen-1);
}

if(str.substring(1,2).equals("x") & !str.substring(0,1).equals("x"))
{
st=str.substring(0,2)+str.substring(2,strLen-1);
}

if(str.substring(0,1).equals("x") | str.substring(1,2).equals("x"))
{
st=str.substring(strLen-2);
}
return st;
  
}

Open in new window


i wrote as above but failing many
Expected	Run		
withoutX2("xHi") → "Hi"	"Hi"	OK	    
withoutX2("Hxi") → "Hi"	"xi"	X	    
withoutX2("Hi") → "Hi"	"null"	X	    
withoutX2("xxHi") → "Hi"	"Hi"	OK	    
withoutX2("Hix") → "Hix"	"null"	X	    
withoutX2("xaxb") → "axb"	"xb"	X	    
withoutX2("xx") → ""	"xx"	X	    
withoutX2("x") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:7)"	X	    
withoutX2("") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:7)"	X	    
withoutX2("Hello") → "Hello"	"null"	X	    
withoutX2("Hexllo") → "Hexllo"	"null"	X	    
withoutX2("xHxllo") → "Hxllo"	"lo"	X	    
other tests
X	

Open in new window

0
 
ozoCommented:
How would you describe what the code in http:#a40567265 is doing?
0
 
zzynxSoftware engineerCommented:
gudii9,
after all those examples you've made using the method substring()
do you know what substring() exactly does and what the two parameters mean?

I second ozo.
Could you please tell us what the following two lines of code are supposed to do?

if(str.substring(0,1).equals("x") & str.substring(1,2).equals("x"))
{
    st=str.substring(strLen-1);
}

Open in new window


Please also be aware of the fact that & and && are two different operators. Do some lookup on the internet concerning these.
0
 
gudii9Author Commented:
public String withoutX2(String str) { 
  

int strLen=str.length();
String st=str;

if(strLen>=2){

if(str.substring(0,1).equals("x") | str.substring(1,2).equals("x"))
{
st=str.substring(strLen-2);
}
}
else{
st=str;
}

return st;
  
}

Open in new window

i see i made some blunders in hurry. I improved my code as above still failing some tests. please advise
Expected	Run		
withoutX2("xHi") → "Hi"	"Hi"	OK	    
withoutX2("Hxi") → "Hi"	"xi"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	"Hi"	OK	    
withoutX2("Hix") → "Hix"	"Hix"	OK	    
withoutX2("xaxb") → "axb"	"xb"	X	    
withoutX2("xx") → ""	"xx"	X	    
withoutX2("x") → ""	"x"	X	    
withoutX2("") → ""	""	OK	    
withoutX2("Hello") → "Hello"	"Hello"	OK	    
withoutX2("Hexllo") → "Hexllo"	"Hexllo"	OK	    
withoutX2("xHxllo") → "Hxllo"	"lo"	X	    
other tests
X	   

Open in new window

0
 
ozoCommented:
Please advise us of how would the code in http:#a40570775 is intended to work.
0
 
zzynxSoftware engineerCommented:
Same question
0
 
gudii9Author Commented:
if(str.substring(0,1).equals("x") | str.substring(1,2).equals("x"))
{
st=str.substring(strLen-2);
}
i thought i was checking x is in first or second position then return substringed string by cutting those x(may be one or 2 depending on x is in first or second or both places)
otherwise return the string as it is.
please correct me where i am doing mistake in my approach.
0
 
ozoCommented:
"checking x is in first or second position"
if(str.substring(0,1).equals("x") | str.substring(1,2).equals("x"))
Yes. (but when do you do that check?)

 "then return substringed string by cutting those"
str.substring(strLen-2);
How does this cut "those"?
0
 
zzynxSoftware engineerCommented:
>> i thought i was checking x is in first or second position
Correct if you replace the bitwise OR operator '|' by the OR operator '||'
But you also need to check if both the first AND the second are 'x'

>> then return substringed string by cutting those x(may be one or 2 depending on x is in first or second or both places)
How could you cover all those situations

xab  ==> cut off the first character
axb  ==>  remove the 2nd character only
xxb  ==>  remove the first two characters

with just one call?
st=str.substring(strLen-2);

Open in new window



Once again, wouldn't it be a good idea to process the corner cases first?

Consider this flow:
1) If the string is the empty string => return it
2) if the string starts with an x => store the part after the x in variable st
2b) if the variable st again starts with an x => return the part after the x
    else return the variable st
3) if 2) isn't true =>
       if the 2nd character is an x => return the concatenation of the first character and the part starting at the 3rd character
4) just return the input string str
0
 
gudii9Author Commented:
Sure. Is it always put above flow in a kind of flow diagam before working on any kind of code challenge at cdehat or real time. Any good tutorials or books on how to put flow or flow diagrams which seems crux of all this effort.  Please advise
0
 
zzynxSoftware engineerCommented:
Just think twice (or even more) before you code. That's all.
0
 
gudii9Author Commented:
ok
0
 
gudii9Author Commented:
str.substring(1,2).equals("x")
Consider this flow:
1) If the string is the empty string => return it
2) if the string starts with an x => store the part after the x in variable st
2b) if the variable st again starts with an x => return the part after the x
    else return the variable st
3) if 2) isn't true =>
       if the 2nd character is an x => return the concatenation of the first character and the part starting at the 3rd character
4) just return the input string st
i kind of got the idea and passed more tests as below but need to think and implement more to be 100% correct
public String withoutX2(String str) { 
int strLen=str.length();
String st=str;
if(strLen==0)
{
return st;
}


if(st.startsWith("x")){
st=str.substring(1);
}

if(st.startsWith("x")){
String st1=str.substring(1);
} else{
st=st;
}

return st;  
}

Open in new window


i fail few tests
Expected	Run		
withoutX2("xHi") → "Hi"	"Hi"	OK	    
withoutX2("Hxi") → "Hi"	"Hxi"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	"xHi"	X	    
withoutX2("Hix") → "Hix"	"Hix"	OK	    
withoutX2("xaxb") → "axb"	"axb"	OK	    
withoutX2("xx") → ""	"x"	X	    
withoutX2("x") → ""	""	OK	    
withoutX2("") → ""	""	OK	    
withoutX2("Hello") → "Hello"	"Hello"	OK	    
withoutX2("Hexllo") → "Hexllo"	"Hexllo"	OK	    
withoutX2("xHxllo") → "Hxllo"	"Hxllo"	OK	    
other tests
X	    

Open in new window

0
 
zzynxSoftware engineerCommented:
2b) if the variable st again starts with an x => return the part after the x
    else return the variable st
When I write return I really mean you should return:

 if(st.startsWith("x")){
    return str.substring(1);
 } else{
    return st;
}

Open in new window


I also called it 2b) because it is supposed to be inside the if of 2)
0
 
zzynxSoftware engineerCommented:
So you already have:

public String withoutX2(String str) { 

   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }

   String st;
   if(str.startsWith("x")){
      st=str.substring(1); // 2) if the string starts with an x => store the part after the x in variable st

      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }

   } else {
      // Up to you to implement 3)
   }

   return str; // 4) just return the input string str
}

Open in new window


Remark the importance of using st instead of str and vice versa!
(I made an error myself at 4))
0
 
gudii9Author Commented:
public String withoutX2(String str) { 

   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }
   String st;
   if(str.startsWith("x")){
      st=str.substring(1); // 2) if the string starts with an x => store the part after the x in variable st

      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }
   } else {
      // Up to you to implement 3)
   }
   return str; // 4) just return the input string str
}

Open in new window


i tried above code failing in one test case
Expected	Run		
withoutX2("xHi") → "Hi"	"Hi"	OK	    
withoutX2("Hxi") → "Hi"	"Hxi"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	"Hi"	OK	    
withoutX2("Hix") → "Hix"	"Hix"	OK	    
withoutX2("xaxb") → "axb"	"axb"	OK	    
withoutX2("xx") → ""	""	OK	    
withoutX2("x") → ""	""	OK	    
withoutX2("") → ""	""	OK	    
withoutX2("Hello") → "Hello"	"Hello"	OK	    
withoutX2("Hexllo") → "Hexllo"	"Hexllo"	OK	    
withoutX2("xHxllo") → "Hxllo"	"Hxllo"	OK	    
other tests

Open in new window


so we have one outer if else containing other inner if-else right?
0
 
zzynxSoftware engineerCommented:
Did you really just take the code I posted and run it?
Did you even read (and try to understand) the code?
Do you really want us to write all the code for you?
0
 
gudii9Author Commented:
public String withoutX2(String str) { 

   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }
   String st;
   if(str.startsWith("x")){
      st=str.substring(1); // 2) if the string starts with an x => store the part after the x in variable st

      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }
      
      
      
      
   } else {
      // Up to you to implement 3)
   }
   return str; // 4) just return the input string str
}

Open in new window

i read and tried the code pasted and run. I still fail one test case as below. please advise

Expected	Run		
withoutX2("xHi") → "Hi"	"Hi"	OK	    
withoutX2("Hxi") → "Hi"	"Hxi"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	"Hi"	OK	    
withoutX2("Hix") → "Hix"	"Hix"	OK	    
withoutX2("xaxb") → "axb"	"axb"	OK	    
withoutX2("xx") → ""	""	OK	    
withoutX2("x") → ""	""	OK	    
withoutX2("") → ""	""	OK	    
withoutX2("Hello") → "Hello"	"Hello"	OK	    
withoutX2("Hexllo") → "Hexllo"	"Hexllo"	OK	    
withoutX2("xHxllo") → "Hxllo"	"Hxllo"	OK	    
other tests
X	    

Open in new window

0
 
ozoCommented:
3) if 2) isn't true =>
       if the 2nd character is an x => return the concatenation of the first character and the part starting at the 3rd character
0
 
zzynxSoftware engineerCommented:
>> i read (...) the code
Then you must have seen that it contains this line
// Up to you to implement 3)

Open in new window


Sorry, but I WON'T write that code for you since I suppose you're here to learn. Well then...
0
 
gudii9Author Commented:
i will try
0
 
gudii9Author Commented:
3) if 2) isn't true =>
       if the 2nd character is an x => return the concatenation of the first character and the part starting at the 3rd character

looks like i forgot or missed this part. let me try to put that also into my code
0
 
gudii9Author Commented:
3) if 2) isn't true =>
       if the 2nd character is an x => return the concatenation of the first character and the part starting at the 3rd character


looks like i forgot or missed this part. let me try to put that also into my code


i tried as below
public String withoutX2(String str) { 
   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }
   String st;
   
   if(str.startsWith("x")){
      st=str.substring(1); // 2) if the string starts with an x => store the part after the x in variable st

      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }
      
      
      
      
   } else {
      if(st.substring(1,2).equals("x")){
         return st.substring(0,1)+st.substring(0,2); 
      }
   }
   return str; // 4) just return the input string str
}

Open in new window


i am missing something getting error as below. please advise
Compile problems:


Error:	if(st.substring(1,2).equals("x")){
	   ^^
The local variable st may not have been initialized


see Example Code to help with compile problems

Open in new window

0
 
ozoCommented:
8:  st=str.substring(1);
is only initialized when
7:  if(str.startsWith("x")){
is true.
When the
19:  } else {
 clause gets run, st has no value in
 20:   if(st.substring(1,2).equals("x")){
0
 
zzynxSoftware engineerCommented:
1) Why do you use variable 'st'? Variable 'str' is the input string. Use that instead.
2) And you don't get "the part starting at the 3rd character" by calling
substring(0,2)

Open in new window

Do you?
0
 
gudii9Author Commented:
public String withoutX2(String str) { 
   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }
   String st;
   
   if(str.startsWith("x")){
      st=str.substring(1); // 2) if the string starts with an x => store the part after the x in variable st

      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }
      
      
      
      
   } else {
      if(str.substring(1,2).equals("x")){
         return str.substring(0,1)+str.substring(2); 
      }
   }
   return str; // 4) just return the input string str
}

Open in new window


now i passed all. I am thinking how changing to str not st fixed my issue.
0
 
gudii9Author Commented:
there is outer if which has inner if else

then there is outer else right.

since we are checking 2nd character after verifying first character in outer if i thought of using st is more meaningful than str. please advise
0
 
ozoCommented:
st is only meaningful when you have assigned a meaning to it.  e.g. with st=str.substring(1);
0
 
gudii9Author Commented:
String st;  
   if(str.startsWith("x")){
      st=str.substring(1);

which i did in outer if loop but that assignmet did not carry over to outer else some reason
0
 
gudii9Author Commented:
how can i improve my code. it looks bit laborious and long. any suggestions? please advise
0
 
ozoCommented:
You only did  8: st=str.substring(1); inside the 7: if(str.startsWith("x")){ ... 19: } not in the 19: else{ ... 23: }
0
 
ozoCommented:
If you want to make use of st in both branches, you might move it out of the conditional:
   if(str.length()==0) { // 1) If the string is the empty string => return it
     return str;
   }
   String st=str.substring(1);
   if( str.startsWith("x") ){
      if(st.startsWith("x")){
         return st.substring(1); // 2b) if the variable st again starts with an x => return the part after the x
      } else{
         return st; // else return the variable st
      }  
   } else {
      if( st.startsWith("x") ){
         return str.substring(0,1)+str.substring(2);
      }
   }
   return str; // 4) just return the input string str

But then doing exactly the same thing at the start of both branches could suggest that other consolidation might be possible

To me, something like this might seem simpler
   String s0=str.length()>0?str.substring(0,1):"";
   String s1=str.length()>1?str.substring(1,2):"";
   String s2=str.length()>2?str.substring(2):"";
   return (s0.equals("x")?"":s0)+(s1.equals("x")?"":s1)+s2;
0
 
gudii9Author Commented:
You only did  8: st=str.substring(1); inside the 7: if(str.startsWith("x")){ ... 19: } 

Open in new window


correct i did there becuase i want to truncate first character  if it is x and assign to st to check second character later in inner else loop


not in the 19: else{ ... 23: }

Open in new window


looks like there also i need to do again in this approach?

I discussed with one of my friend he wrote as below which seems effective by using replace function


public String withoutX2(String str) {

String strN="";

if("".equals(str))

return strN;

else    

strN=str.length()>1?(str.substring(0, 2).replace("x", "")+str.substring(2)):str.substring(0, 1).replace("x", "");

return strN;

  

}

Open in new window

0
 
ozoCommented:
//or
int len=Math.min(str.length(),2);
return str.substring(0, len).replace("x", "")+str.substring(len);
0
 
zzynxSoftware engineerCommented:
>> how can i improve my code.
>> it looks bit laborious and long.
It's not because it looks laborious and long that it is bad and needs to be improved.
Code in java should
1) do what it is intended for (Check)
2) be good readable and hence good maintainable by yourself and others (Check)

No need to change.
Unless you better understand any shorter form.
But it is not better code because it is shorter.
0
 
gudii9Author Commented:
String s0=str.length()>0?str.substring(0,1):"";
   String s1=str.length()>1?str.substring(1,2):"";
   String s2=str.length()>2?str.substring(2):"";
   return (s0.equals("x")?"":s0)+(s1.equals("x")?"":s1)+s2;

Open in new window


i was not clear on the return statement esp bracker opening and closing which is bit confusing. Can you please elborate. By the way above also passed all tests
0
 
gudii9Author Commented:
public String withoutX2(String str) {


int len=Math.min(str.length(),2);
return str.substring(0, len).replace("x", "")+str.substring(len);



  

}

Open in new window

above also passed all tests. Can you please elaborate on the return statement?
0
 
ozoCommented:
str.substring(0, len) is the part from which x should be removed
str.substring(0, len).replace("x", "") is the part with x removed
str.substring(len) is the part that should return unchanged

(or, could you elaborate on the return statement of http:#a40601762, as an example of the elaboration you want?)
0
 
gudii9Author Commented:
str.substring(len) is the part that should return unchanged

say string is xxabc
then str becomes abc right on that we are doiing substring of(2)?
we supposed to return abc as result.


str.substring(0, len) is the part from which x should be removed
i got this part as we have to remove from first two as 2 is min of 5 and 2.
str.substring(0, len).replace("x", "") is the part with x removed
until index 1(ie index 0 and index 1) if you find x then replace it with ""
after replacing does str becomes abc or it remain xxabc when it comes to
>>>str.substring(len) is the part that should return unchanged<<

please advise
0
 
ozoCommented:
Strings are immutable.
withoutX2("xxabc") does not actually alter the original "xxabc" but returns a new string "abc"
str.substring(0, len).replace("x", "") does not actually alter the original str.substring(0, len) but returns a new string
str.substring(0, len) does not not actually alter the original str but returns a new string

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29
0
 
gudii9Author Commented:
since the StringBuilder is mutable i expected below to throw index out of bound but it surprisingly passed all tests. please advise

public String withoutX2(String str) {
StringBuilder sb=new StringBuilder(str);
int len=Math.min(sb.length(),2);
return sb.substring(0, len).replace("x", "")+sb.substring(len);

}

xaxb
becomes
xa
becomes
a till fist part of return stmt


a+a.substring(2);===>ideally should show index outofbound but did not throw.

Open in new window

please advise
0
 
ozoCommented:
Good question, and good experiment, but sb.substring returns a String, not a StringBuilder
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#substring%28int%29
0
 
gudii9Author Commented:
So there is no use of string builder instrad of string here right. In which scenario it is better to use string builder instread of string? Please advise
0
 
ozoCommented:
Here is one way to use StringBuilder
public String withoutX2(String str) {
  StringBuilder sb=new StringBuilder(str);
  if( sb.length()>1 && sb.charAt(1)=='x' ){
     sb.deleteCharAt(1);
  }
  if( sb.length()>0 && sb.charAt(0)=='x' ){
     sb.deleteCharAt(0);
  }
  return sb.toString();
}

Open in new window

(Do you see why charAt(1) was tried before charAt(0)?)
0
 
gudii9Author Commented:
Not sure. I too wonder. Please advise
0
 
ozoCommented:
What do you think would happen if they were done in the other order?
0
 
gudii9Author Commented:
i see first you are deleting x if it is at index 1 then coming backwards(rather than usual forward route)
you are deleting x if it is at index 0.

If it is in opposite way like below
deleting x if it is at index 0.
then deleting x if it is at index 1//since sb is mutable since above character already deleted 0 now when we try to delete at index 1 on newly truncated string builder i think it deletes adjacent unwated character

I think to avoid that you delted first at index 1  then deleting at index 0 since index 0 will never change even after truncating .

Please correct me if i am wrong.
0
 
ozoCommented:
You are correct.
0
 
gudii9Author Commented:
public String withoutX2(String str) {
StringBuilder sb=new StringBuilder(str);
int len=Math.min(sb.length(),2);
return sb.substring(0, len).replace("x", "")+sb.substring(len);

}

Open in new window


i still wonder how above one worked.

Say string is "hx"
len is 2 as sb.length() is 2 and min of 2,2 is 2
now in return statement what is happening?

return sb.substring(0, len).replace("x", "")+sb.substring(len);

return sb.substring(0, len).replace("x", "")//replaces x at second posistion with empty //string====>sb.substring(0, 2).replace("x", "")---resulsts "h"
+sb.substring(len);//sb.substring(2)--->h.substring(2)...should throw null pointer exception? but //passing all tests. But i also see your point that substring returns string but not able to connect all //these dots. please advise
0
 
ozoCommented:
sb.substring(0, len) is an immutable  String, not a mutable StringBuilder
so replacing it returns a value but does not change its operand
0
 
gudii9Author Commented:
Say string is "hx"
len is 2 as sb.length() is 2 and min of 2,2 is 2
now in return statement what is happening?

return sb.substring(0, len).replace("x", "")+sb.substring(len);

return sb.substring(0, len).replace("x", "")//replaces x at second posistion with empty //string====>sb.substring(0, 2).replace("x", "")---resulsts "h"

above is correct right?
How second part---->+sb.substring(len); is useful here?

please advise
0
 
ozoCommented:
sb.substring(0, len).replace("x", "")
does not change sb
0
 
gudii9Author Commented:
sb.substring(len);

what this part of the code in return statement does?
please advise
0
 
gudii9Author Commented:
public String withoutX2(String str) {
StringBuilder sb=new StringBuilder(str);
int len=Math.min(sb.length(),2);
return sb.substring(0, len).replace("x", "");

}

Open in new window


without that line also i passed some tests and failed some
Expected	Run		
withoutX2("xHi") → "Hi"	"H"	X	    
withoutX2("Hxi") → "Hi"	"H"	X	    
withoutX2("Hi") → "Hi"	"Hi"	OK	    
withoutX2("xxHi") → "Hi"	""	X	    
withoutX2("Hix") → "Hix"	"Hi"	X	    
withoutX2("xaxb") → "axb"	"a"	X	    
withoutX2("xx") → ""	""	OK	    
withoutX2("x") → ""	""	OK	    
withoutX2("") → ""	""	OK	    
withoutX2("Hello") → "Hello"	"He"	X	    
withoutX2("Hexllo") → "Hexllo"	"He"	X	    
withoutX2("xHxllo") → "Hxllo"	"H"	X	    
other tests
X	    

Open in new window

0
 
ozoCommented:
See http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#substring%28int%29
It returns a String that contains the characters from sb starting at len
0
 
gudii9Author Commented:
i see the point
return sb.substring(0, len).replace("x", "")//takes care of first 2 characters and removes x if it is there +sb.substring(len);//takes care of characters 3rd onwards and returns them as it is to concatenate to previous result. Please correct me if i am wrong
0
 
gudii9Author Commented:
public String withoutX2(String str) {
//StringBuilder sb=new StringBuilder(str);
int len=Math.min(str.length(),2);
return str.substring(0, len).replace("x", "")+str.substring(len);

}

Open in new window


is equalivalent to below in this case. Functionally no different right

public String withoutX2(String str) {
StringBuilder sb=new StringBuilder(str);
int len=Math.min(str.length(),2);
return sb.substring(0, len).replace("x", "")+sb.substring(len);

}

Open in new window


In above two code snippets which approach is better?
 please advise
0
 
ozoCommented:
Yes.  (but it only removes x from the result, not from the operand)
0
 
ozoCommented:
In http:#a40614954 the only thing that happens with the StringBuilder object is that String objects are extracted from it.  So I see no point to converting to StringBuilder only to convert back to String.
The mutability of a StringBuilder is never used.
0
 
gudii9Author Commented:
deleteCharAt
public StringBuilder deleteCharAt(int index)
Removes the char at the specified position in this sequence. This sequence is shortened by one char.
Note: If the character at the given index is a supplementary character, this method does not remove the entire character. If correct handling of supplementary characters is required, determine the number of chars to remove by calling Character.charCount(thisSequence.codePointAt(index)), where thisSequence is this sequence.

Parameters:
index - Index of char to remove
Returns:
This object.
Throws:
StringIndexOutOfBoundsException - if the index is negative or greater than or equal to length().

this method wont return String right(since delete operation) similar to substring.

So we do not have that problem with below code

public String withoutX2(String str) {
  StringBuilder sb=new StringBuilder(str);
  if( sb.length()>1 && sb.charAt(1)=='x' ){
     sb.deleteCharAt(1);
  }
  if( sb.length()>0 && sb.charAt(0)=='x' ){
     sb.deleteCharAt(0);
  }
  return sb.toString();
}

Open in new window


So we are able to use mutability feature of string builder?please advise
0
 
ozoCommented:
Yes, http:#a40615016 does use the mutability feature of StringBuilder
0
 
gudii9Author Commented:
 if( sb.length()>1 && sb.charAt(1)=='x' ){
     sb.deleteCharAt(1);
  }

Open in new window


>>> sb.deleteCharAt(1);//after deleting character we do not need to assing back to sb right
sb= sb.deleteCharAt(1);

It will implicitly do that?
0
 
ozoCommented:
Yes
0
 
zzynxSoftware engineerCommented:
Thanx 4 axxepting
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 32
  • 24
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now