Solved

removing a character from string

Posted on 2014-09-24
34
168 Views
Last Modified: 2014-10-05
Hi

I am trying below example

http://codingbat.com/prob/p190570


I wrote my code as below
public String missingChar(String str, int n) {
if(0<=n & n<=(str.length()-1)){
//str.charAt(n)
char o=str.charAt(n);

return str.replace("o","");
//a.replace("o","");
}



  return null;
}

Open in new window


I wonder what is the easy, simple, readable way of writing code for this. Please advise
0
Comment
Question by:gudii9
  • 15
  • 6
  • 5
  • +2
34 Comments
 
LVL 26

Accepted Solution

by:
dpearson earned 125 total points
ID: 40343194
How about this?

public String missingChar(String str, int n) {
   // Get the string up to the 'n'-th character
   // Add the string from the 'n+1'-th character to the end
  return str.substring(0, n) + str.substring(n+1) ;
}
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 125 total points
ID: 40343442
I'd do:  
public String missingChar(String str, int n) {
    return new StringBuilder(str).deleteCharAt(n).toString();
}

Open in new window

You might be interested to see the bytecode produced by the above (called '_missingChar' below) with Coding Bat's 'answer'

  public java.lang.String _missingChar(java.lang.String, int);
    Code:
       0: new           #2                  // class java/lang/StringBuilder
       3: dup           
       4: aload_1       
       5: invokespecial #3                  // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
       8: iload_2       
       9: invokevirtual #4                  // Method java/lang/StringBuilder.deleteCharAt:(I)Ljava/lang/StringBuilder;
      12: invokevirtual #5                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      15: areturn       

  public java.lang.String missingChar(java.lang.String, int);
    Code:
       0: aload_1       
       1: iconst_0      
       2: iload_2       
       3: invokevirtual #6                  // Method java/lang/String.substring:(II)Ljava/lang/String;
       6: astore_3      
       7: aload_1       
       8: iload_2       
       9: iconst_1      
      10: iadd          
      11: invokevirtual #7                  // Method java/lang/String.substring:(I)Ljava/lang/String;
      14: astore        4
      16: new           #2                  // class java/lang/StringBuilder
      19: dup           
      20: invokespecial #8                  // Method java/lang/StringBuilder."<init>":()V
      23: aload_3       
      24: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      27: aload         4
      29: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      32: invokevirtual #5                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      35: areturn       

Open in new window

0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 125 total points
ID: 40344121
Your initial idea is ok. I corrected your mistakes. The following code passes all the tests.
public String missingChar(String str, int n) {
if(0<=n && n<=(str.length()-1)){ //use && instead of &
    char o = str.charAt(n);
    return str.replace(Character.toString(o),""); // two Strings for parameters here
}
  return "error: n out of range";
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40346268
return str.replace(Character.toString(o),""); // two Strings for parameters here(why the resulted word do not have enpty space as we are replacing  'o'
with "")

return str.replace("o","");


How above two lines are different.

what is the meaning of Character.toString(o)
Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40346279
How is "" is different from " "(with space)
0
 
LVL 7

Author Comment

by:gudii9
ID: 40346286
I see all above three solutions are great. How to decide which one among possible 'n' number of solutions for a given challenge is best one in java(esp in real time projects). Please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40346587
I see all above three solutions are great. How to decide which one among possible 'n' number of solutions for a given challenge is best one in java(esp in real time projects). Please advise
Either mine or CEHJ's solution are the "best ones" as they are both one line and simple to understand.

Clear code is usually what you should be looking for.

Doug
0
 
LVL 27

Expert Comment

by:rrz
ID: 40347202
How above two lines are different.
return str.replace("o","");

Open in new window

 That line is in your original code at the top.  It replaces the String "o" with the empty String. But, that is not what you wanted to do. You wanted to replace the character that is located at index n in the String str.  
return str.replace(Character.toString(o),"");
In that line, I used the static method toString of the Character class. I used it to convert the char variable o(that is the name you gave it) into a String.  The replace method of String will not accept a char.
public String replace(CharSequence target,
             CharSequence replacement)

Open in new window

You see it needs a CharSequence for the target and the replacement. The String class implements the CharSequence.
I said your solution was ok because it passed all the tests that they made on it. But, actually it is not a good solution because the replace method will replace each occurrence of the char value(the targets) in the str String. If they had tested  missingChar("kitten", 2)     then it would have failed. It would have replaced both "t"s
How is "" is different from " "(with space)
"" is an empty String. It is a String with nothing in it. Even though it is empty it is still a String. " " is a String with a single space character in it.
I see all above three solutions are great.
I wouldn't describe my rewrite of your code "great" because it has an error in logic. I just posted it to show you where you went wrong. Although it passes the tests, it does have a nasty bug in it.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40347244
How is "" is different from " "
How is "The real ways I saw it" different from "There always is a wit"
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40347348
:)
0
 
LVL 7

Author Comment

by:gudii9
ID: 40355507
spacing is different

"There always is a wit"

Above line is wrongly having the empty spaces. they are put at the place where they supposed to not put them. Still i did not understand how above one related to below question
How is "" is different from " "

Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40355535
"" is an empty String. It is a String with nothing in it.

I just got time to read earlier posts detailedly

When do we need to use

"" is an empty String. It is a String with nothing in it.

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40355547
How is "" is different from " "
spacing is different
0
 
LVL 27

Expert Comment

by:rrz
ID: 40356103
When do we need to use
An empty String comes in handy in several situations.  In this question, we used it replace a character with nothing.  In your other question,
http://www.experts-exchange.com/Programming/Languages/Java/Q_28526482.html#a40347253 
we used it to force Java to create a String from the series of characters.  The same thing could be done with integers. For example
String s = "" + 1 + 2;

Open in new window

This will create a String equal to "12".
0
 
LVL 7

Author Comment

by:gudii9
ID: 40357663
How is "" is different from " "

spacing is different

can i say like
" " one unit of space(not sure what we call this unit??) empty sting
"" means  empty string with zero unit of space empty sting
"  " two units of space(not sure what we call this unit may be two tabs of space as i clicked tab twice on my laptop??)

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40357708
I would not call " " empty string
I would call "" empty string
0
 
LVL 7

Author Comment

by:gudii9
ID: 40357729
I would not call " " empty string

can we call it string with null content?
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 7

Author Comment

by:gudii9
ID: 40357740
public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Test2 t=new Test2();
        System.out.println(t.front3(null));
        
	}
		public String front3(String str){
			  if(str.length()<=3){
			      return str+str+str;
			  }
			   else{
			      String str2 = "" + str.charAt(0) + str.charAt(1) + str.charAt(2);
			      return str2+str2+str2;
			   }

        }
	}

Open in new window


I got Null pointer exception when i ran as above

public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Test2 t=new Test2();
        System.out.println(t.front3(""));
        
	}
		public String front3(String str){
			  if(str.length()<=3){
			      return str+str+str;
			  }
			   else{
			      String str2 = "" + str.charAt(0) + str.charAt(1) + str.charAt(2);
			      return str2+str2+str2;
			   }

        }
	}          

Open in new window


when i ran as above i do not get any output in console. I do not get any exception also. simply blank console

public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Test2 t=new Test2();
        System.out.println(t.front3(" "));
        
	}
		public String front3(String str){
			  if(str.length()<=3){
			      return str+str+str;
			  }
			   else{
			      String str2 = "" + str.charAt(0) + str.charAt(1) + str.charAt(2);
			      return str2+str2+str2;
			   }

        }
	}          

Open in new window


when i ran as above  i do not get any output in console. I do not get any exception also. simply blank console.

What is the difference between above 3 cases?
please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40357896
The first incorrectly passes null instead of String,
the second prints a newline.
the third prints three spaces and a newline.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40358196
null is not a string?
how null different from ""

the second prints a newline.

why it prints new line?
Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40358205
the third prints three spaces and a newline.

How do i verify three spaces. I see my cursor in the newline of eclipse when i click on the console which make sense but i cannot validate three spaces. please advise
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40358238
Use the following method to show spaces or normal strings

public static void print(String s) {
   System.out.printf("'%s'%n", s);
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40358252
public class aa {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       // Test2 t=new Test2();
       // System.out.println(t.front3(null));
		front3();
		print("");
		print(" ");
		print(null);
	}
	
	public static void front3(){
	
	String str="hello";
	char[] charArray=str.toCharArray();
	int indexOfLastChar=charArray.length-1;
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];
	charArray[1]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;
	}
	String reversedStr=new String(charArray);
	System.out.println("actual string "+str+" reversed string "+reversedStr);
		
	}
	
	
	public static void print(String s) {
		   System.out.printf("'%s'%n", s);
		}
}

Open in new window


i wrote as above
i got output as below on console
actual string hello reversed string hlloh
''
' '
'null'


why i have not got null pointer exception
also hello reverse should be olleh which is not coming. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40358608
when i passed null as below

print(null);

why i did not get null pointer exception or illegal argument exception since the method is expecting string and i am passing null. still i did not see any exception like NPE or IAE
Please advise
0
 
LVL 27

Expert Comment

by:rrz
ID: 40358669
" " one unit of space(not sure what we call this unit??)
It a String containing one space character.
"  " two units of space(not sure what we call this unit may be two tabs of space as i clicked tab twice on my laptop??)
It is a String with two space characters. I pressed my space bar twice. A tab is something different.  
can we call it string with null content?
No, it is an empty  String.
why i did not get null pointer exception or illegal argument exception since the method is expecting string and i am passing null.
null is a literal.  Look at (in middle of page)
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40358676
With

  print(null)

you're passing null to this method:

      public static void print(String s) {
               System.out.printf("'%s'%n", s);
            }

It turns out that printf() and all of the Java print methods are written to handle being passed a null value.

The code in System.out.printf() end up looking like this:

{
if (argument == null)
   System.out.println("null") ;
else
  System.out.println(argument) ;
}

So there's no error.

Does that make sense?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40361731
"'%s'%n"

what is the meaning of above code. Please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40361772
"'%s'%n"
what is the meaning of above code. Please advise

That was code I just copied from your original example.  What it means, when used like this:

System.out.printf("%s%n",myString) ;

Is that you read through the format string ("%s%n") and follow each pair of letters as a command for how to build up the sting to print.

In this case "%s" is replaced by the string you passed in (the variable myString in this example).
And "%n" is replaced by a newline.

String myString = "hello" ;
System.out.printf("%s%n",myString) ;

just prints out

hello

A simpler version of the same code would avoid printf and just use println like this:

String myString = "hello" ;
System.out.println(myString) ;

which does the exact same thing as the printf example.  Just more simply.

You can read a lot more about printf here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

but it's pretty complicated stuff.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362447
No, it is an empty  String.

Empty string could be of 0 space or 1 space or 2 space or 100space right.

No matter how many spaces we still call it empty string right. Null is different and it is default string literal right which would not lead to null pointer exception similar to how empty string lead to it. Please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40362586
Generally people only call a string with no characters in it (no spaces, nothing) an "empty string".

So we have these 3 possibilities:

String nullString = null ;
String emptyString = "" ;
String nonEmptyString = "      " ;

And yes - null is different and can lead to null pointer exceptions, which an empty string will not do.

emptyString.length() ; // Returns 0
emptyString.isEmpty() ; // Returns true
nonEmptyString.length() ; // Returns > 0
nonEmptyString.isEmpty() ; // Returns false

nullString.length() ; // Throws null pointer exception - since nullString is null

Doug
0
 
LVL 27

Expert Comment

by:rrz
ID: 40362792
I agree with Doug. If a String contains a space character, then it is not empty.
Null is different and it is default string literal right which would not lead to null pointer exception similar to how empty string lead to it
 I think the first part of that sentence is right. As you can read in the "Java Language  Specification" at
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5   
I think the second part of that sentence is wrong. But, it is not clear as what you are saying there.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362814
String nonEmptyString = "      " ;

nonEmptyString could contain bunch of spaces or bunch of characters as well right. Whether space or character it does not matter right they all are nonEmptyStrings with length >=1.
Please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 125 total points
ID: 40362818
Empty string is ""
Any other string is a non-empty string.

emp·ty
adjective \ˈem(p)-tē\
: containing nothing
http://www.merriam-webster.com/dictionary/empty
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40362824
Whether space or character it does not matter right they all are nonEmptyStrings with length >=1.

Yes that's right.

If the length() function returns >= 1 then it's not empty.  It doesn't matter what characters are in the string.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

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 explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

867 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now