Solved

last 3 characters of string to capital letter

Posted on 2014-10-10
33
150 Views
Last Modified: 2014-10-15
Hi,

I am trying below challenge

http://codingbat.com/prob/p125268

I wrote as below

public String endUp(String str) {

if(str.length()<=3){
return str.toUpperCase();
}


if(str.length()>=3){
String str1=str.substring(0,4);
return str1.toUpperCase();
}
return null;
  
}

Open in new window


I see some test cases failing

Expected      Run            
endUp("Hello") → "HeLLO"      "HELL"      X         
endUp("hi there") → "hi thERE"      "HI T"      X         
endUp("hi") → "HI"      "HI"      OK         
endUp("woo hoo") → "woo HOO"      "WOO "      X         
endUp("xyz12") → "xyZ12"      "XYZ1"      X         
endUp("x") → "X"      "X"      OK         
endUp("") → ""      ""      OK         


How to improve and fix above program. Please advise
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
  • 16
  • 9
  • 4
  • +2
33 Comments
 
LVL 7

Author Comment

by:gudii9
ID: 40373206
how to capitalize the last 3 characters of string bigger than 3 characters. Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40373222
public String endUp(String str) {

if(str.length()<=3){
return str.toUpperCase();
}


if(str.length()>=3){
String str1=str.substring(Math.max(0, str.length() - 3));

return str1.toUpperCase();
}
return null;
  
}

Open in new window


i tried as above based on my search but got failed test cases as below

Expected      Run            
endUp("Hello") → "HeLLO"      "LLO"      X         
endUp("hi there") → "hi thERE"      "ERE"      X         
endUp("hi") → "HI"      "HI"      OK         
endUp("woo hoo") → "woo HOO"      "HOO"      X         
endUp("xyz12") → "xyZ12"      "Z12"      X         
endUp("x") → "X"      "X"      OK         
endUp("") → ""      ""      OK         


Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40373231
How  below line giving last 3 characters of string
String str1=str.substring(Math.max(0, str.length() - 3));
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Accepted Solution

by:
CEHJ earned 167 total points
ID: 40373342
Substringing isn't really appropriate, since no part of the String should be cut off

public String endUp(String str) {
   StringBuilder sb = new StringBuilder(str);
   int replaced = 0;
   for(int i = sb.length();--i>=0 && replaced < 3;) {
     char c = sb.charAt(i);
     sb.setCharAt(i, Character.toUpperCase(c));
     replaced++;
   } 
   return sb.toString();
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40373548
Is there is a way i can do without using StringBuilder. Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40373553
Yes, there is a way.

Your attempts are getting closer.  What is missing from the ones that are wrong, and how can you add that piece.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40373602
I need to add front part of the string that is mising. I somehow need to get that and attach in the front
0
 
LVL 7

Author Comment

by:gudii9
ID: 40373604

String str1=str.substring(Math.max(0, str.length() - 3));

I was not clear on above line how it is giving last 3 characters of string. please advise.

what is the need of Math.max here
0
 
LVL 84

Expert Comment

by:ozo
ID: 40373775
Math.max is useful when str.length() - 3 can be negative
0
 
LVL 7

Author Comment

by:gudii9
ID: 40373982
oh got it
0
 
LVL 7

Author Comment

by:gudii9
ID: 40375263
public class Test11 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        endUp("hello");

	}

	
	public static  String endUp(String str) {

		if(str.length()<=3){
		return str.toUpperCase();
		}


		if(str.length()>=3){
			
			
			
		String str1=str.substring(Math.max(0, str.length() - 3));
		String str2=str.substring(0, (str.length() - 3));
		return str2+str1.toUpperCase();
		}
		return null;
		  
		}
}

Open in new window


I wrote as above and all test cases seems happy




Show output only (no red/green)
prev  |  next  |  chance   |  CodingBat  >  Warmup-1      
Expected      Run            
endUp("Hello") → "HeLLO"      "HeLLO"      OK         
endUp("hi there") → "hi thERE"      "hi thERE"      OK         
endUp("hi") → "HI"      "HI"      OK         
endUp("woo hoo") → "woo HOO"      "woo HOO"      OK         
endUp("xyz12") → "xyZ12"      "xyZ12"      OK         
endUp("x") → "X"      "X"      OK         
endUp("") → ""      ""      OK         

I wonder how to avoid null

How my code is looking. Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40375355
I might consider the if(str.length()>=3){ superfluous.  CEHJ might consider the string concatenation inefficient.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40377083
public class Test12 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        endUp("hello");

	}

	
	public static  String endUp(String str) {

		if(str.length()<=3){
		return str.toUpperCase();
		}


	//	if(str.length()>=3){
			
			
			
		String str1=str.substring(Math.max(0, str.length() - 3));
		String str2=str.substring(0, (str.length() - 3));
		return str2+str1.toUpperCase();
		//}
		//return null;
		  
		}
}

Open in new window


I wrote as above and tests cases all of them passing

Expected      Run            
endUp("Hello") → "HeLLO"      "HeLLO"      OK         
endUp("hi there") → "hi thERE"      "hi thERE"      OK         
endUp("hi") → "HI"      "HI"      OK         
endUp("woo hoo") → "woo HOO"      "woo HOO"      OK         
endUp("xyz12") → "xyZ12"      "xyZ12"      OK         
endUp("x") → "X"      "X"      OK         
endUp("") → ""      ""      OK
0
 
LVL 7

Author Comment

by:gudii9
ID: 40377187
for(int i = sb.length();--i>=0 && replaced < 3;) {


in the above line what is the importance of below code

&& replaced < 3

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40378386
It stops the loop when 3 characters have been replaced
0
 
LVL 16

Assisted Solution

by:krakatoa
krakatoa earned 167 total points
ID: 40378790
You don't need any loops for this stuff; take another approach :

public String endUp(String str) {
  
  String temp = str;
  str = str.toUpperCase();
  str = str.length()>2?str.replace(str.substring(0,str.length()-3),temp.substring(0,str.length()-3)):str;
    
  return str;
    }

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40379021
for(int i = sb.length();--i>=0 && replaced < 3;) {

Is increment operator missing in above code.  As usually for loop is in below format ?(assignment;condition;increment)
for(i=0;i<n;i++)
0
 
LVL 7

Author Comment

by:gudii9
ID: 40379024
str = str.length()>2?str.replace(str.substring(0,str.length()-3),temp.substring(0,str.length()-3)):str;

I was not very clear on above line.

If string length is greater than 2 is true then do  str.replace(str.substring(0,str.length()-3)
If string length is greater than 2 is false then do temp.substring(0,str.length()-3)):str

what is meaing of temp.substring(0,str.length()-3)):str

why we are using temp?
Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40379065
Is increment operator missing in above code.  As usually for loop is in below format ?(assignment;condition;increment)
Yes, the increment part of the for(init;condition;increment)statement; is empty,
however, the --i in the condition part, and the replaced++ in the statement both serve the role.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40379074
what is meaing of temp.substring(0,str.length()-3)):str
It is part of the ternary conditional expression operator condition?value1:value2
str.length()>2?str.replace(str.substring(0,str.length()-3),temp.substring(0,str.length()-3)):str;
Here str.length()>2 is the condition,
str.replace(str.substring(0,str.length()-3),temp.substring(0,str.length()-3)) is value1, and str is value2
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40379352
To expand on what ozo has explained : the ternary operator evaluates an expression to true or false. We only need to know whether the string is at least 3 characters long, (i.e. more than 2), - (or not) - then we can take the appropriate action.

Since we can copy the original string very easily by copying it to "temp", we can now capitalise the entire passed-in string, and replace the part of it that should NOT be in caps, with the correct length substring from "temp" (which holds a copy of the original, lower case version). And if the passed-in string was 2 characters long or less, then we just return the (already) uppercased version of it.
0
 
LVL 32

Expert Comment

by:awking00
ID: 40379828
One statement will do it -

public String endUp(String str) {

return str.length() <= 3? str.toUpperCase() : str.substring(0,str.length() - 3)
                                    + str.substring(str.length() - 3,str.length)).toUpperCase();
}
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40379926
Yes that would be a refinement. But the last length will cause a compile error as it is missing parentheses.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40379947
public class Test15 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=endUp("hello");
		System.out.println("str3==>"+str3);

	}

	public static String endUp(String str) {
		   StringBuilder sb = new StringBuilder(str);
		   int replaced = 0;
		   for(int i = sb.length();--i>=0 && replaced < 3;) {
		     char c = sb.charAt(i);
		     sb.setCharAt(i, Character.toUpperCase(c));
		     replaced++;
		   } 
		   return sb.toString();
		}
}

Open in new window


i wonder why we need two counters like i and also replaced. please advise

return str.length() <= 3? str.toUpperCase() : str.substring(0,str.length() - 3)
                                    + str.substring(str.length() - 3,str.length)).toUpperCase();

above line is more easy to understand for me.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40379952
public class Test15 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=endUp("hello");
		System.out.println("str3==>"+str3);

	}
	public static String endUp(String str) {

		return str.length() <= 3? str.toUpperCase() : str.substring(0,str.length() - 3)
		                                    + str.substring(str.length() - 3,str.length()).toUpperCase();
		}
}

Open in new window


above also worked fine after adding one bracket '('
0
 
LVL 32

Expert Comment

by:awking00
ID: 40380135
Sorry for the bad typing. As krakatoa pointed out and you discovered.... - 3, str.length)) should have been ... - 3, str.length())
0
 
LVL 84

Expert Comment

by:ozo
ID: 40380165
The reason for two counters was that --i>=0 stops the loop when you get to the start of the string, and replaced  < 3 stops the loop after replacing 3 characters.
Presumably this was more easy for the author of that code to understand,
but when you write your code you probably want to choose a way that's more easy for you.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40380404
--i>=0 stops the loop when you get to the start of the string,

i thought we supposed to start the loop when we get to start of the string. I am not clear on this. please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 166 total points
ID: 40381232
That particular loop started at the end of the string, with int i = sb.length()


i thought we supposed to
Different people may approach problems differently.
I think this is a good thing because if we all thought the same way, we would never learn anything, and a problem that stumped one of us would stump everyone.
Eventually you will develop your own preferred styles, but it can still behoove you to be exposed to other styles.  It can help you understand other people's solutions, and it can give you more flexibility to choose styles according to how well they fit particular types of problems.
On the other hand, you don't need to learn every method at once, and you may want to concentrate first on what makes sense to you until you get comfortable with it and have a base to expand from.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40381266
can we move the replaced into the for loop in the place of initialization along with 'i' initialization like

for(int replaced = 0 && int i = sb.length();--i>=0 && replaced < 3;)

Open in new window


Also in the conditional statement of for loop is there is limit on how many conditions we can check(like above we are checking two conditions)?
0
 
LVL 84

Expert Comment

by:ozo
ID: 40381283
In Java, that would be an improper use of &&
but you could do it like
for(int replaced = 0, i = sb.length();--i>=0 && replaced < 3;){ }

There is no limit on how many conditions we can check, but too many may become confusing, and may suggest a rethink.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40381727
Personally i'd never go above 2 or it starts becoming unreadable
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40381885
and a problem that stumped one of us would stump everyone.


That is a good statement.

And as mega-Savant CEHJ often exhorts, the important thing is being sure of your objective.
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

The purpose of this article is to demonstrate how we can use conditional statements using Python.
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

734 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