Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

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

removing a character from string

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
gudii9
Asked:
gudii9
  • 15
  • 6
  • 5
  • +2
4 Solutions
 
dpearsonCommented:
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
 
CEHJCommented:
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
 
rrzCommented:
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
Technology Partners: 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!

 
gudii9Author Commented:
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
 
gudii9Author Commented:
How is "" is different from " "(with space)
0
 
gudii9Author Commented:
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
 
dpearsonCommented:
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
 
rrzCommented:
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
 
ozoCommented:
How is "" is different from " "
How is "The real ways I saw it" different from "There always is a wit"
0
 
CEHJCommented:
:)
0
 
gudii9Author Commented:
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
 
gudii9Author Commented:
"" 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
 
ozoCommented:
How is "" is different from " "
spacing is different
0
 
rrzCommented:
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
 
gudii9Author Commented:
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
 
ozoCommented:
I would not call " " empty string
I would call "" empty string
0
 
gudii9Author Commented:
I would not call " " empty string

can we call it string with null content?
0
 
gudii9Author Commented:
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
 
ozoCommented:
The first incorrectly passes null instead of String,
the second prints a newline.
the third prints three spaces and a newline.
0
 
gudii9Author Commented:
null is not a string?
how null different from ""

the second prints a newline.

why it prints new line?
Please advise
0
 
gudii9Author Commented:
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
 
CEHJCommented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
rrzCommented:
" " 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
 
dpearsonCommented:
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
 
gudii9Author Commented:
"'%s'%n"

what is the meaning of above code. Please advise
0
 
dpearsonCommented:
"'%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
 
gudii9Author Commented:
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
 
dpearsonCommented:
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
 
rrzCommented:
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
 
gudii9Author Commented:
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
 
ozoCommented:
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
 
dpearsonCommented:
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

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.

  • 15
  • 6
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now