?
Solved

substring example to delte string

Posted on 2014-10-04
26
Medium Priority
?
284 Views
Last Modified: 2014-10-09
Hi

I am trying below challenge

http://codingbat.com/prob/p100905

I wrote as below


public String delDel(String str) {
  if((str.substring(1)).equals("del")){
  return str-"del";
  }
  return str;
}


what is the best way to see 'del' is there in given string and delete from exact same location. 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
  • 11
  • 4
  • 4
  • +2
26 Comments
 
LVL 84

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 40361587
return str.replaceFirst("(?<=^.)del","");
0
 
LVL 28

Accepted Solution

by:
dpearson earned 400 total points
ID: 40361711
You can't use the "-" operator to remove the string.

But you can build up the string with a piece missing like this:
  return str.substring(0, pos) + str.substring(pos+3) ;
which returns the string to position 'pos', plus the string from 'pos+3' to the end - which means the string but with 3 characters removed at position 'pos'.

Using that you can do this:

public String delDel(String str) {
  int pos = str.indexOf("del") ;
  if (pos == -1 || pos != 1)
     return str ;
  return str.substring(0, pos) + str.substring(pos+3) ;
}
0
 
LVL 7

Author Comment

by:gudii9
ID: 40361726
?<=^.

what is meaning of above code.

Is it is some kind of regular expression. Please advise
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
LVL 28

Assisted Solution

by:rrz
rrz earned 400 total points
ID: 40361736
First let's explain your errors.
if((str.substring(1)).equals("del")){

Open in new window

This won't work because str.substring(1) is the entire String minus the first character.
return str-"del";

Open in new window

This won't work because you can't use the - operator in that way. You can use the + operator for concatenating Strings. But you can't subtract with - operator.  ozo's solution is good.  But, the following is easier to understand.
public String delDel(String str) {
    if(str.length()>3 && (str.substring(1,4)).equals("del")){
       return str.replaceFirst("del","");
   }
   return str;
}

Open in new window

0
 
LVL 28

Expert Comment

by:rrz
ID: 40361742
Using dpearson's and ozo's ideas, here is another solution.
public String delDel(String str) {
    if(str.indexOf("del") == 1){       
         return str.replaceFirst("del","");
    }
    return str; 
}

Open in new window

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 800 total points
ID: 40362161
Another way:
public String delDel(String str) {
   StringBuilder sb = new StringBuilder(str);
   int ixDel = sb.indexOf("del");
   return ixDel == 1? sb.delete(ixDel, 4).toString() : str;
}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 40362245
Or, if you want to avoid calling StringBuilder unnecessarily:
   return str.indexOf("del") == 1? new StringBuilder(str).delete(1, 4).toString() : str;
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40362259
He he - good one ;)
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362401
 if (pos == -1 || pos != 1)


why are we checking pos is not equal to 1 as above. Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362414
 return str.indexOf("del") == 1? new StringBuilder(str).delete(1, 4).toString() : str;

Open in new window


why are we checking indexOf("del") is 1 or not as above then if it then delete(1,4). Otherwise return same string

Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362427
return ixDel == 1? sb.delete(ixDel, 4).toString() : str;

Open in new window



why we have given 4 as argument of delete method. I thought it should have been 3.



All the test cases passed as below

public String delDel(String str) {
   StringBuilder sb = new StringBuilder(str);
   int ixDel = sb.indexOf("del");
   return ixDel == 1? sb.delete(ixDel, 4).toString() : str;
}

Open in new window


Expected      Run            
delDel("adelbc") → "abc"      "abc"      OK         
delDel("adelHello") → "aHello"      "aHello"      OK         
delDel("adedbc") → "adedbc"      "adedbc"      OK         
delDel("abcdel") → "abcdel"      "abcdel"      OK         
delDel("add") → "add"      "add"      OK         
delDel("ad") → "ad"      "ad"      OK         
delDel("a") → "a"      "a"      OK         
delDel("") → ""      ""      OK         
delDel("del") → "del"      "del"      OK         
delDel("adel") → "a"      "a"      OK         
delDel("aadelbb") → "aadelbb"
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362438
str.replaceFirst("del","");

Open in new window


I was checking the API
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

I wonder why there is no replaceLast method similar to replaceFirst.
Please advise
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40362507
if (pos == -1 || pos != 1)
why are we checking pos is not equal to 1 as above. Please advise

The problem said "if the string "del" appears starting at index 1" so checking if (pos != 1) is checking for whether the string is at index 1.

Looking at this I realize I made it more complex than it needs to be because of course if "pos == -1" then that means "pos != 1" is true, so we can just write this as:

if (pos != 1) ...

I wonder why there is no replaceLast method similar to replaceFirst.
This is just because the people who wrote Java (Sun) thought that it would be more common for people to want to replace the first string that matches a pattern rather than the last string.  When designing classes and methods there's a lot of asking "how will people most often want to use this" and that shows up in the design.  They certainly could have added a "replaceLast" method.  They just didn't think it would be used that often.

Doug
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40362511
why are we checking indexOf("del") is 1 or not as above then if it then delete(1,4). Otherwise return same string

Please advise

Because that is what's specified
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362832
return str.replaceFirst("(?<=^.)del","");

what is meaning of ?<=^.

Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362834
I checked api

String      replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement

It did not talk about ?<=^.

please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40362835
0
 
LVL 7

Author Comment

by:gudii9
ID: 40362836
i need to read it more
0
 
LVL 28

Expert Comment

by:rrz
ID: 40362864
To explain (?<=^.)del  
You could read
http://www.regular-expressions.info/lookaround.html
0
 
LVL 7

Author Comment

by:gudii9
ID: 40366183
public String delDel(String str) {
   StringBuilder sb = new StringBuilder(str);
   int ixDel = sb.indexOf("del");
   return ixDel == 1? sb.delete(ixDel, 4).toString() : str;
}


As above it is all working fine.
Below line

return ixDel == 1? sb.delete(ixDel, 4).toString() : str;

why we have given 4 as argument of delete method. I thought it should have been 3.
0
 
LVL 28

Expert Comment

by:rrz
ID: 40366308
Look at the API  
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#delete(int,%20int)   
it says
end - The ending index, exclusive.
Therefore the end index is excluded from the delete.
So, if we want to delete "del" at index 1,2,3,  then we should use 4 for end
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40367206
Yeah - the key part as rrz mentioned is that the "end index" does NOT include that position.

This is true for all of the string operations.

So delete(0,1) means "delete the character starting at position 0 and ending BEFORE position 1" - so just 1 character at position 0.

etc.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40367521
replace
public StringBuilder replace(int start,
                    int end,
                    String str)
Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)
Parameters:
start - The beginning index, inclusive.
end - The ending index, exclusive.
str - String that will replace previous contents.
Returns:
This object.
Throws:
StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

I see replace function also has end exclusive.

What other functions of String has end as exclusive apart from delete, replace. please advise
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40367549
Any string function that takes a range (e.g. substring) always has the end index being exclusive.

It would be very confusing if some of them weren't.  They're all the same.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40368328
StringBuilder      delete(int start, int end)
Removes the characters in a substring of this sequence.

I see one other in StringBuilder with end exclusive
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 800 total points
ID: 40368340
I see one other in StringBuilder with end exclusive
That's the point - the end is exclusive
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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 second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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…
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.
Suggested Courses

762 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