Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

starOut java challenge

Hi,
I am working on below challenge
http://codingbat.com/prob/p139564
I tried my code as below
public String starOut(String str) {
return str.replaceAll("./*.","");
  
}

Open in new window

I am getting below result
Expected      Run            
starOut("ab*cd") → "ad"      "d"      X         
starOut("ab**cd") → "ad"      ""      X         
starOut("sm*eilly") → "silly"      ""      X         
starOut("sm*eil*ly") → "siy"      "y"      X         
starOut("sm**eil*ly") → "siy"      ""      X         
starOut("sm***eil*ly") → "siy"      "y"      X         
starOut("stringy*") → "string"      ""      X         
starOut("*stringy") → "tringy"      ""      X         
starOut("*str*in*gy") → "ty"      ""      X         
starOut("abc") → "abc"      "c"      X         
starOut("a*bc") → "c"      ""      X         
starOut("ab") → "ab"      ""      X         
starOut("a*b") → ""      "b"      X         
starOut("a") → "a"      "a"      OK         
starOut("a*") → ""      ""      OK         
starOut("*a") → ""      ""      OK         
starOut("*") → ""      "*"      X         
starOut("") → ""      ""      OK         
other tests
X         

how to  improve my approach, results and design of this challenge. How do i make a graphical venn or flow chart or some other relevant diagram to design it before writing code to decide best strategy?
 Please advise
SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
When it comes to regular expressions navigate to https://regex101.com/
It gives you a nice explanation of the regex you type in and you can try it out on several examples.
Avatar of gudii9

ASKER

i like below site

https://regex101.com/


but not sure how to use it.

For this challengfe i tried as attached but not able to proceed.

where to enter the string and solution regular expression and where to see results and where to see errors or problems, explanation.
please advise
regex.png
In regex101.com you only enter the regular expression, not the Java code that would use the regular expression:
https://regex101.com/r/uO8jU2/1
Also since you are not in a Java "quoted" string, you don't need to use Java "" string escape sequences.
(The pcre regular expression and replacement notation is also slightly different from Java notation)
https://regex101.com/r/uO8jU2/2
Avatar of gudii9

ASKER

what is testing string and substitution
what is pcre?
what is pcre?
You know Google, right? If you Google that, the first link is this one
Avatar of gudii9

ASKER

In regex101.com you only enter the regular expression, not the Java code that would use the regular expression:
https://regex101.com/r/uO8jU2/1
Also since you are not in a Java "quoted" string, you don't need to use Java "" string escape sequences.
(The pcre regular expression and replacement notation is also slightly different from Java notation)
https://regex101.com/r/uO8jU2/2

how to execute code from above site.

I do not see any button like Run etc to execute modified or updated code?
please advise
Avatar of gudii9

ASKER

public String starOut(String str) {
return str.replaceAll("//*.","");
 
}

why above did not replace * with ""

i expected starOut("ab*cd") → "abcd"
/ is not the same as \
https://regex101.com/r/uO8jU2/3
Avatar of gudii9

ASKER

public String starOut(String str) {
return str.replaceAll("\\*.","");
 
}

this also gave



i expected abcd not abd.

i wonder why i got abd?plese advise
Avatar of gudii9

ASKER

public String starOut(String str) {
return str.replaceAll("\\*","");
 
}

above gave abcd for ab*cd
why i got abd
because the . matched the c
Avatar of gudii9

ASKER

i see under substitution there is separate section without heading to see output as given below

https://regex101.com/r/uO8jU2/2
valuesOutput.jpg
Avatar of gudii9

ASKER

key is backward slash as \ not forward slash as /

also
.?\*+.?
what is meaning of above line?



/.?\*+.?/g

above line what is meaning of g

if i replace g with gudii9 why i am getting below error



EXPLANATION
/.?\*+.?/gudii9
Errors are explained from left to right. Move the mouse cursor over them to see the error highlighted in your pattern
d-modifier does not exist in PCRE (PHP) (or is not yet supported by regex101.com)
9-modifier does not exist in PCRE (PHP) (or is not yet supported by regex101.com)
Duplicate modifier: i


please advise
The stuff inside the / / is the pattern, the stuff after the final / are modifiers.
The only modifiers it understood were the g the i the u
Since using the i modifier twice means the same thing as using it once, it gives you a warning in case you did this unintentionally.
   /.?\*+.?/gui
        .? matches any character (except newline) [unicode]
            Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
        \*+ matches the character * literally
            Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
        .? matches any character (except newline) [unicode]
            Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
        g modifier: global. All matches (don't return on first match)
        u modifier: unicode: Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters
        i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Avatar of gudii9

ASKER

The only modifiers it understood were the g the i the u

        g modifier: global. All matches (don't return on first match)
        u modifier: unicode: Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters
        i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])


when to use g and when to use u and when to use i.

when i used i as below results are almost same not sure how changing g to i as modifier changed results?



/.?\*+.?/i
.? matches any

ab*cd
ab**cd
sm*eilly
sm*eil*ly
sm**eil*ly
sm***eil*ly
stringy*
*stringy
*str*in*gy
 
gave below results

ad
ab**cd
sm*eilly
sm*eil*ly
sm**eil*ly
sm***eil*ly
stringy*
*stringy
*str*in*gy



Since using the i modifier twice means the same thing as using it once, it gives you a warning in case you did this unintentionally.
Avatar of gudii9

ASKER

/.?\*+.?/g
for below

ab*cd
ab**cd
sm*eilly
sm*eil*ly
sm**eil*ly
sm***eil*ly
stringy*
*stringy
*str*in*gy



gave below results

ad
ad
silly
siy
siy
siy
string
tringy
ty
Avatar of gudii9

ASKER

EXPLANATION
/.?\*+.?/u

for below

ab*cd
ab**cd
sm*eilly
sm*eil*ly
sm**eil*ly
sm***eil*ly
stringy*
*stringy
*str*in*gy


gave below results

ad
ab**cd
sm*eilly
sm*eil*ly
sm**eil*ly
sm***eil*ly
stringy*
*stringy
*str*in*gy
Avatar of gudii9

ASKER

only g modifier is giving consistent correct results but not i  or u.

why cannot i use say a, b, c or x, y, z but only g, u, i?
>> why cannot i use say a, b, c or x, y, z but only g, u, i?
You really mean this?
That's the same as asking why you can't use  
3 § 4 

Open in new window

if you want to multiplicate 3 and 4.
That's convention.
You can see the modifiers that regex101.com recognizes
by hovering over the ? in the grey circle in the modifier box
or by clicking on flags/modifiers in the QUICK REFERENCE box
Avatar of gudii9

ASKER

i see list of valid modifiers as attached.

any simple easy learning book or site on regular expressions to learn sequentially and systematically?
Modifiers.png
Learn Regular Expressions with simple, interactive exercises: http://regexone.com/
Lots of background information on regular expressions: http://www.regular-expressions.info/

Warning: Regular expressions are not simple.
Avatar of gudii9

ASKER

http://regexone.com/lesson/letters_and_digits

above site is good. i am going through it.
Avatar of gudii9

ASKER

http://regexone.com/lesson/wildcards_dot


Exercise 2: Matching With Wildcards
Task      Text       
Match      cat.      Success
Match      896.      Success
Match      ?=+.      Success
Skip      abc1      Failed



i wonder why
.

failed last test as attached.

where as \. meta period character passed all 4 tests including last abc1 test also
period.png
Avatar of gudii9

ASKER

http://regexone.com/lesson/character_ranges

what is difference between below two??
[A-Za-z0-9_]
[A-Za-z0-9]
It should skip that last line, not match.
With . (any character) it matches.

But guidi, I'm not gonna answer anymore regular expression questions in this thread.
In this thread we were talking about a java program.
Avatar of gudii9

ASKER

http://regexone.com/lesson/repeating_characters
i wonder why last test failed as attached
z{1,3}
repetition.png
Avatar of gudii9

ASKER

also wonder why first two tests failed for

 .{1,3}
repeate1to3.png
Avatar of gudii9

ASKER

i wonder what is difference between kleen star and kleen plus
why
\d+
failed all above tests as attached.


why
\d*
failed last test alone?
please advise
KleenStar.png
Avatar of gudii9

ASKER

http://regexone.com/lesson/kleene_operators

also

why
 .*

failed all tests in above link?
i tough a satisfied below rule

 .* (zero or more of any character).
Avatar of gudii9

ASKER

i wonder why the first test failed as attached with below

file?s

http://regexone.com/lesson/optional_characters
optiona.png
Avatar of gudii9

ASKER

http://regexone.com/lesson/whitespaces

I wonder why below failed test 1 and test 3  as attached.

\t
tab.png
Avatar of gudii9

ASKER

what is diference between tab..when i say 1tab2 then when i say backspace gives 12 though
Avatar of gudii9

ASKER

http://regexone.com/lesson/line_beginning_end

why first test fails as attached for
$l
startEnd.png
Avatar of gudii9

ASKER

http://regexone.com/lesson/capturing_groups

what is meaning of below

Imagine for example that you had a command line tool to list all the image files you have in the cloud. You could then use a pattern such as ^(IMG\d+\.png)$ to capture and extract the full filename, but if you only wanted to capture the filename without the extension, you could use the pattern ^(IMG\d+)\.png$ which only captures the part before the period.

please advise
Avatar of gudii9

ASKER

http://regexone.com/lesson/nested_groups

what is this nested groups? when we use it?
Lesson 12: Nested groups
When you are working with complex data, you can easily find yourself having to extract multiple layers of information, which can result in nested groups. Generally, the results of the captured groups are in the order in which they are defined (in order by open parenthesis).

Take the example from the previous lesson, of capturing the filenames of all the image files you have in a list. If each of these image files had a sequential picture number in the filename, you could extract both the filename and the picture number using the same pattern by writing an expression like ^(IMG(\d+))\.png$ (using a nested parenthesis to capture the digits).

The nested groups are read from left to right in the pattern, with the first capture group being the contents of the first parentheses group, etc.

For the following strings, write an expression that matches and captures both the full date, as well as the year of the date.

Exercise 12: Matching Nested Groups
Task      Text      Capture Groups       
Capture      Jan 1987      Jan 1987 1987      To be completed
Capture      May 1969      May 1969 1969      To be completed
Capture      Aug 2011      Aug 2011 2011
please advise
Avatar of gudii9

ASKER

not clear on below group work as well

http://regexone.com/lesson/more_groups
Lesson 13: More group work
As you saw in the previous lessons, all the quantifiers including the star *, plus +, repetition {m,n} and the question mark ? can all be used within the capture group patterns. This is the only way to apply quantifiers on sequences of characters instead of the individual characters themselves.

For example, if I knew that a phone number may or may not contain an area code, the right pattern would test for a the existence of the whole group of digits (\d{3})? and not the individual characters themselves (which would be wrong).

Depending on the regular expression engine you are using, you can also use non-capturing groups which will allow you to match the group but not have it show up in the results.

Below are a couple different common display resolutions, try to capture the width and height of each display.

Exercise 13: Matching Nested Groups
Task      Text      Capture Groups       
Capture      1280x720      1280 720      To be completed
Capture      1920x1600      1920 1600      To be completed
Capture      1024x768      1024 768
Avatar of gudii9

ASKER

not clear on below conditional as well

Lesson 14: It's all conditional
As we mentioned before, it's always good to be precise, and that applies to coding, talking, and even regular expressions. For example, you wouldn't write a grocery list for someone to Buy more .* because you would have no idea what you'd could get back. Instead you would write Buy more milk or Buy more bread, and in regular expressions, we can actually define these conditionals explicitly.

Specifically when using groups, you can use the | (logical OR, aka. the pipe) to denote different possible sets of characters. In the above example, I can write the pattern "Buy more (milk|bread|juice)" to match only the strings Buy more milk, Buy more bread, or Buy more juice.

Like normal groups, you can use any sequence of characters or metacharacters in a condition, for example, ([cb]ats*|[dh]ogs?) would match either cats or bats, or, dogs or hogs. Writing patterns with many conditions can be hard to read, so you should consider making them separate patterns if they get too complex.

Go ahead and try writing a conditional pattern that matches only the lines with small fuzzy creatures below.

Exercise 14: Matching Conditional Text
Task      Text       
Match      I love cats      To be completed
Match      I love dogs      To be completed
Skip      I love logs      To be completed
Skip      I love cogs
Avatar of gudii9

ASKER

http://regexone.com/lesson/misc_meta_characters

Additionally, there is a special metacharacter \b which matches the boundary between a word and a non-word character. It's most useful in capturing entire words (for example by using the pattern \w+\b).

One concept that we will not explore in great detail in these lessons is back referencing, mostly because it varies depending on the implementation. However, many systems allow you to reference your captured groups by using \0 (usually the full matched text), \1 (group 1), \2 (group 2), etc. This is useful for example when you are in a text editor and doing a search and replace using regular expressions to swap two numbers, you can search for "(\d+)-(\d+)" and replace it with "\2-\1" to put the second captured number first, and the first captured number second for example.

Below are a number of different strings, try out the different types of metacharacters or anything we've learned in the previous lessons and continue on when you are ready.

not clear on above please advise
There are many questions here which are not relevant to the original challenge, and which would be more appropriate in separate questions in a different topic area.
As I said: time to close this question an open another thread about regular expressions.
Avatar of gudii9

ASKER

sure i will do that
Avatar of gudii9

ASKER

one question relating to this challenge.
how to write solution for this challenge without using regular expression?
please advise
You iterate over the input string character by character and add each character to the resulting string.
Whenever you encounter a '*', you remove the last character of the result string and skip the next character of the input string.
Up to you to come with the code that does this. As an excercise.
Whenever you encounter a '*', you remove the last character of the result string and skip the next character of the input string.
If you do it that way, be careful about the case where there are multiple adjacent stars.
Right.
And "be careful" translates into:
Check EVERY character you skip in the input string.
If (and only if) that is another '*' then skip an extra character in the input string.
Avatar of gudii9

ASKER

how to solve this challenge without using regex? please advise
>> please advise
I did.
Avatar of gudii9

ASKER

what is the comment id for the solution without regex?. I may have missed it
Avatar of gudii9

ASKER

i see only 2 comments without non reg solution? can you please advise if i am missing some comment
Avatar of gudii9

ASKER

any suggestion on non regex solution for this challenge?
ID: 41539395
Avatar of gudii9

ASKER

You iterate over the input string character by character and add each character to the resulting string.
Whenever you encounter a '*', you remove the last character of the result string and skip the next character of the input string.
Up to you to come with the code that does this. As an excercise.
ok i see your comment
Avatar of gudii9

ASKER

public String starOut(String str) {
return str.replaceAll("\\*","");
for(int i=0;i<=str.length();i++){
  String result=""+str.substring(i,i+1);
  
}
  
}


//You iterate over the input string character by character and add each character 
//to the resulting string.
//Whenever you encounter a '*', you remove the last character of the result 
//string and skip the next character of the input string.
//Up to you to come with the code that does this. As an excercise.

Open in new window


something like above?
Avatar of gudii9

ASKER

public class StartOutChallenge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//And "be careful" translates into: 
		//	Check EVERY character you skip in the input string. 
		//	If (and only if) that is another '*' then skip an extra character in the 
		//input string.
		System.out.println("value is-->"+starOut("ab*cd"));

	}
	
	public static String starOut(String str) {
		//return str.replaceAll("\\*","");
		String result="";
		for(int i=0;i<=str.length()-1;i++){
		  result=result+str.substring(i,i+1);
		}
		return result;
		  
		}

}

Open in new window


i tried as above and got below output
value is-->ab*cd
This code
String result="";
for(int i=0;i<=str.length()-1;i++){
  result=result+str.substring(i,i+1);
}
return result;

Open in new window


implements this:
//You iterate over the input string character by character and add each character
//to the resulting string.

Now you should add this too:
//Whenever you encounter a '*', you remove the last character of the result
//string and skip the next character of the input string.
Check EVERY character you skip in the input string.
If (and only if) that is another '*' then skip an extra character in the input string.
Avatar of gudii9

ASKER

public class StartOutChallenge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//And "be careful" translates into: 
		//	Check EVERY character you skip in the input string. 
		//	If (and only if) that is another '*' then skip an extra character in the 
		//input string.
		System.out.println("value is-->"+starOut("ab*cd"));

	}
	
	public static String starOut(String str) {
		//return str.replaceAll("\\*","");
		String result="";
		for(int i=0;i<=str.length()-1;i++){
			if(str.charAt(i)!='*'){
		  result=result+str.substring(i,i+1);
			}
			
		}
		return result;
		  
		}

}

Open in new window

i tried as above got below output
abcd

but not sure how to ad by removing bc?
You should try to literally do what I posted.
You already had this:
// You iterate over the input string character by character and add each character to the resulting string.
by using this code:

String result="";
for(int i=0;i<=str.length()-1;i++){
  result=result+str.substring(i,i+1);
}

Open in new window


Now you should add:
1. Whenever you encounter a '*', you remove the last character of the result string
and
2. skip the next character of the input string
3. Check EVERY character you skip in the input string
    If (and only if) that is another '*' then skip an extra character in the input string.

In your last code you tried to add point 1. by adding an extra condition for adding the encountered character. Trust me, that's NOT the same.
Try to do exactly what I said.
Try adding point 1 and come back with your code.
Although http://codingbat.com/prob/p139564 does not check for this case, doing exactly what is said in http:#a41559357 may produce questionable results for starOut("abc*d*e*f")
Avatar of gudii9

ASKER

public class StartOutChallenge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//And "be careful" translates into: 
		//	Check EVERY character you skip in the input string. 
		//	If (and only if) that is another '*' then skip an extra character in the 
		//input string.
		System.out.println("value is-->"+starOut("ab*cd"));

	}
	
	public static String starOut(String str) {
		//return str.replaceAll("\\*","");
		String result="";
		String result2="";
		String result3="";
		for(int i=0;i<=str.length()-1;i++){
			if(str.charAt(i)!='*'){
		  result=result+str.substring(i,i+1);
			}	
			else(str.charAt(i)=='*'){
				result2=str.substring(0,i);
				result3=str.substring(i,str.length());
				result=result2+result3;
			}
		}
		return result;		  
		}

}
/*Now you should add:
1. Whenever you encounter a '*', you remove the last character of the result string 
and
2. skip the next character of the input string
3. Check EVERY character you skip in the input string
    If (and only if) that is another '*' then skip an extra character in the input string. 
In your last code you tried to add point 1. by adding an extra condition for adding 
the encountered character. Trust me, that's NOT the same.
Try to do exactly what I said.
Try adding point 1 and come back with your code.*/

Open in new window


gtting below error.


Multiple markers at this line
      - Syntax error, insert "AssignmentOperator Expression" to complete
       Assignment
      - The left-hand side of an assignment must be a variable
      - Syntax error, insert ";" to complete Statement

please advise on how to fix


Although http://codingbat.com/prob/p139564 does not check for this case, doing exactly what is said in http:#a41559357 may produce questionable results for starOut("abc*d*e*f")

Open in new window


cannot we do this challenge without regex approach?
I suppose you know what is wrong with this line:

if (...) {
} else (str.charAt(i)=='*'){    // <<<<<<<< this line
}

Open in new window


If not:
it's or
if (...) { 
   ...
} else {
   ...
}

Open in new window

or
if (...) {
   ...
} else if (...) {
   ...
}

Open in new window

In other words: each condition must be preceeded by an 'if'.

Once again, would you be so kind as to pay attention to the right indentation!
Avatar of gudii9

ASKER

public class StartOutChallenge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// And "be careful" translates into:
		// Check EVERY character you skip in the input string.
		// If (and only if) that is another '*' then skip an extra character in
		// the
		// input string.
		System.out.println("value is-->" + starOut("ab*cd"));

	}

	public static String starOut(String str) {
		// return str.replaceAll("\\*","");
		String result = "";
		String result2 = "";
		String result3 = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			if (str.charAt(i) != '*') {
				result = result + str.substring(i, i + 1);
			} else if (str.charAt(i) == '*') {
				result2 = str.substring(0, i);
				result3 = str.substring(i, str.length());
				result = result2 + result3;
			}
		}
		return result;
	}

}
/*
 * Now you should add: 1. Whenever you encounter a '*', you remove the last
 * character of the result string and 2. skip the next character of the input
 * string 3. Check EVERY character you skip in the input string If (and only if)
 * that is another '*' then skip an extra character in the input string. In your
 * last code you tried to add point 1. by adding an extra condition for adding
 * the encountered character. Trust me, that's NOT the same. Try to do exactly
 * what I said. Try adding point 1 and come back with your code.
 */

Open in new window


i see mistake i made no if after else
Avatar of gudii9

ASKER

In other words: each condition must be preceeded by an 'if'.

except last else which do not need condition right?
if (){}
else(){}
else{}
Avatar of gudii9

ASKER

public class StartOutChallenge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// And "be careful" translates into:
		// Check EVERY character you skip in the input string.
		// If (and only if) that is another '*' then skip an extra character in
		// the
		// input string.
		System.out.println("value is-->" + starOut("ab*cd"));

	}

	public static String starOut(String str) {
		// return str.replaceAll("\\*","");
		String result = "";
		String result2 = "";
		String result3 = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			if (str.charAt(i) != '*') {
				result = result + str.substring(i, i+1);
				System.out.println("result in if-->"+result);
			} else if (str.charAt(i) == '*') {
				result2 = str.substring(0, i);
				System.out.println("result2 in else-->"+result2);
				result3 = str.substring(i, str.length());
				System.out.println("result2 in if-->"+result2);
				result = result2 + result3;
				System.out.println("result3 in if-->"+result3);
			}
		}
		return result;
	}

}
/*
 * Now you should add: 1. Whenever you encounter a '*', you remove the last
 * character of the result string and 2. skip the next character of the input
 * string 3. Check EVERY character you skip in the input string If (and only if)
 * that is another '*' then skip an extra character in the input string. In your
 * last code you tried to add point 1. by adding an extra condition for adding
 * the encountered character. Trust me, that's NOT the same. Try to do exactly
 * what I said. Try adding point 1 and come back with your code.
 */

Open in new window


i modified further and got as below
result in if-->a
result in if-->ab
result2 in else-->ab
result2 in if-->ab
result3 in if-->*cd
result in if-->ab*cdc
result in if-->ab*cdcd
value is-->ab*cdcd


still something is not right
except last else which do not need condition right?
Right. (no condition, so no else)

still something is not right
Indeed.

First a remark (not related with the fact that it doesn't work):

No need to write:
if (str.charAt(i) != '*') {
   ...
} else if (str.charAt(i) == '*') {
   ...
}

Open in new window


You can omit the 2nd condition (if the character is NOT different from a star, it IS a star, no?)
if (str.charAt(i) != '*') {
   ...
} else {
   ...
}

Open in new window


About your code still not working, could you indicate for the lines of code you write which of the following points they try to fulfill?
1. Whenever you encounter a '*', you remove the last character of the result string
2. skip the next character of the input string
3. Check EVERY character you skip in the input string
    If (and only if) that is another '*' then skip an extra character in the input string.
Avatar of gudii9

ASKER

You can omit the 2nd condition (if the character is NOT different from a star, it IS a star, no?)
i agree

1. Whenever you encounter a '*', you remove the last character of the result string
2. skip the next character of the input string
3. Check EVERY character you skip in the input string
    If (and only if) that is another '*' then skip an extra character in the input string.

i am not sure on how to write above?
please advise
I'm trying to help you writing java.
Don't ask me to write it for you.
Please answer my question: In the code you wrote and posted, please indicate (in a comment next to each line) what you were trying to accomplish.
Avatar of gudii9

ASKER

1. Whenever you encounter a '*', you remove the last character of the result string
2. skip the next character of the input string
3. Check EVERY character you skip in the input string
    If (and only if) that is another '*' then skip an extra character in the input string.

to accomplish enumuration or list iterator or just plain string or sting builder or string buffer or some other better approach i can use right?
wht is best approach to start writing code?
I asked you to indicate in this code:
	public static String starOut(String str) {
		// return str.replaceAll("\\*","");
		String result = "";
		String result2 = "";
		String result3 = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			if (str.charAt(i) != '*') {
				result = result + str.substring(i, i+1);
				System.out.println("result in if-->"+result);
			} else if (str.charAt(i) == '*') {
				result2 = str.substring(0, i);
				System.out.println("result2 in else-->"+result2);
				result3 = str.substring(i, str.length());
				System.out.println("result2 in if-->"+result2);
				result = result2 + result3;
				System.out.println("result3 in if-->"+result3);
			}
		}
		return result;
	}

Open in new window


what you wanted to accomplish with each line.
Avatar of gudii9

ASKER

public String starOut(String str) {
// return str.replaceAll("\\*","");
		String result = "";
		String result2 = "";
		String result3 = "";
		for (int i = 0; i <= str.length() - 1; i=i+2) {//go to next star by moving  characters
			if (str.charAt(i) != '*') {
				result = result + str.substring(i, i++);
			//	System.out.println("result in if-->"+result);
			} else if (str.charAt(i) == '*') {//step 1 i am doing here
				result2 = str.substring(0, i);//step 2 skipping after *part and keeping before star
			//	System.out.println("result2 in else-->"+result2);
		//		result3 = str.substring(i, str.length());//keeping after star part
			//	System.out.println("result2 in if-->"+result2);
				result = result2_result3;//concatenating before and after star parts
			//	System.out.println("result3 in if-->"+result3);
			}
		}
		return result;
}
//1.Whenever you encounter a '*', you remove the last character of the result string 
//2. //skip the next character of the input string
//3. Check EVERY character you skip in the input string
  //  If (and only if) that is another '*' then skip an extra character in the input string.

//You iterate over the input string character by character and add each character 
//to the resulting string.
//Whenever you encounter a '*', you remove the last character of the result 
//string and skip the next character of the input string.
//Up to you to come with the code that does this. As an excercise.

Open in new window


still not able to answer and implement your 3 questions
public String starOut(String str) {
// return str.replaceAll("\\*","");
		String result = "";
		String result2 = "";
		String result3 = "";
		for (int i = 0; i <= str.length() - 1; i=i+2) {//go to next star by moving  characters
			if (str.charAt(i) != '*') {
				result = result + str.substring(i, i++);
			//	System.out.println("result in if-->"+result);
			} else if (str.charAt(i) == '*') {//step 1 i am doing here
				result2 = str.substring(0, i);//step 2 skipping after *part and keeping before star
			//	System.out.println("result2 in else-->"+result2);
		//		result3 = str.substring(i, str.length());//keeping after star part
			//	System.out.println("result2 in if-->"+result2);
				result = result2+result3;//concatenating before and after star parts
			//	System.out.println("result3 in if-->"+result3);
			}
		}
		return result;
}
//1.Whenever you encounter a '*', you remove the last character of the result string 
//2. //skip the next character of the input string
//3. Check EVERY character you skip in the input string
  //  If (and only if) that is another '*' then skip an extra character in the input string.

//You iterate over the input string character by character and add each character 
//to the resulting string.
//Whenever you encounter a '*', you remove the last character of the result 
//string and skip the next character of the input string.
//Up to you to come with the code that does this. As an excercise.

Open in new window


i am passing all non star cases and faiing miserably on star cases as still stugling to get thoughts going in right direction
Expected      Run            
starOut("ab*cd") → "ad"      ""      X      
starOut("ab**cd") → "ad"      "ab*"      X      
starOut("sm*eilly") → "silly"      ""      X      
starOut("sm*eil*ly") → "siy"      "sm*eil"      X      
starOut("sm**eil*ly") → "siy"      "sm*"      X      
starOut("sm***eil*ly") → "siy"      "sm***eil"      X      
starOut("stringy*") → "string"      ""      X      
starOut("*stringy") → "tringy"      ""      X      
starOut("*str*in*gy") → "ty"      ""      X      
starOut("abc") → "abc"      ""      X      
starOut("a*bc") → "c"      ""      X      
starOut("ab") → "ab"      ""      X      
starOut("a*b") → ""      ""      OK      
starOut("a") → "a"      ""      X      
starOut("a*") → ""      ""      OK      
starOut("*a") → ""      ""      OK      
starOut("*") → ""      ""      OK      
starOut("") → ""      ""      OK      
other tests
X      
So, for clearness sake, if I remove all commented lines, I get:

public String starOut(String str) {
   String result = "";
   String result2 = "";
   String result3 = "";
   for (int i = 0; i <= str.length() - 1; i=i+2) { //go to next star by moving  characters
       if (str.charAt(i) != '*') {
           result = result + str.substring(i, i++);
       } else if (str.charAt(i) == '*') { //step 1 i am doing here
           result2 = str.substring(0, i); //step 2 skipping after *part and keeping before star
           result = result2_result3; //concatenating before and after star parts
       }
   }
   return result;
}

Open in new window


As the first step I told you to "iterate over the input string character by character and add each character to the resulting string"
You wrote this line:
for (int i = 0; i <= str.length() - 1; i=i+2)

Open in new window

My question: why do you increment i by 2 in each iteration?

Let's go step by step.
When the instruction is: "iterate over the input string character by character and add each character to the resulting string"
then this is the corresponding code:

public String starOut(String str) {
   String result = "";
   for (int i = 0; i <= str.length()-1; i++) { // iterate over the input string character by character
       result = result + str.substring(i, i++); // add each character to the resulting string
   }
   return result;
}

Open in new window


When you run this code, you'll see that this method just outputs the input string.
That's as expected at this stage.
Now, let's move on.

Starting from the above code, now I ask you to add the next step being:
1. Whenever you encounter (during the iteration) a '*', you remove the last character of the result string

public String starOut(String str) {
   String result = "";
   for (int i = 0; i <= str.length()-1; i++) { // iterate over the input string character by character
       if (str.charAt(i) == '*') { // Whenever I encounter a '*'
             result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0); // remove the last character of the result string
       } else {
             result = result + str.substring(i, i++); // add each character to the resulting string
       }
   }
   return result;
}

Open in new window


Remark:
If I ask you to remove the last character of the result string, you should normally write
result = result.substring(0, result.length()-1);

Open in new window

However, the result string could be empty at that moment and to cover that corner case, we write instead:
result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0);

Open in new window


Now having the above code, let's add the next step:
2. and skip the next character of the input string

public String starOut(String str) {
   String result = "";
   for (int i = 0; i <= str.length()-1; i++) { // iterate over the input string character by character
       if (str.charAt(i) == '*') { // Whenever I encounter a '*'
             result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0); // remove the last character of the result string
             .......   // skip the next character of the input string
       } else {
             result = result + str.substring(i, i++); // add each character to the resulting string
       }
   }
   return result;
}

Open in new window


Up to you: what instruction should do that?
Avatar of gudii9

ASKER

now it is more clear.

On the last step you mean as below?
public String starOut(String str) {

   String result = "";
   for (int i = 0; i <= str.length()-1; i++) { // iterate over the input string character by character
       if (str.charAt(i) == '*') { // Whenever I encounter a '*'
             result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0); // remove the last character of the result string
               result = result.substring(0, result.length()-2 > 0 ? result.length()-2 : 0);// // skip the next character of the input string...you mean penultimate (one before last character of result string right?
             
       } else {
             result = result + str.substring(i, i++); // add each character to the resulting string
       }
   }
   return result;
}

Open in new window

Expected      Run            
starOut("ab*cd") → "ad"      ""      X      
starOut("ab**cd") → "ad"      ""      X      
starOut("sm*eilly") → "silly"      ""      X      
starOut("sm*eil*ly") → "siy"      ""      X      
starOut("sm**eil*ly") → "siy"      ""      X      
starOut("sm***eil*ly") → "siy"      ""      X      
starOut("stringy*") → "string"      ""      X      
starOut("*stringy") → "tringy"      ""      X      
starOut("*str*in*gy") → "ty"      ""      X      
starOut("abc") → "abc"      ""      X      
starOut("a*bc") → "c"      ""      X      
starOut("ab") → "ab"      ""      X      
starOut("a*b") → ""      ""      OK      
starOut("a") → "a"      ""      X      
starOut("a*") → ""      ""      OK      
starOut("*a") → ""      ""      OK      
starOut("*") → ""      ""      OK      
starOut("") → ""      ""      OK      
other tests
NO!

If this code
result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0);

Open in new window

is removing the last character of the result string
then how on earth could this
result = result.substring(0, result.length()-2 > 0 ? result.length()-2 : 0);

Open in new window

be skip the next character of the input string

Please think.
We're iterating over the input string. What should you do to skip one character?

Remark:
it's absolutely useless to run this incomplete method against the tests on that site.
We're building a complete solution step by step. As long as it is not complete, you know it won't fulfill all tests.
Avatar of gudii9

ASKER


Please think.
We're iterating over the input string. What should you do to skip one character?

i did not understood the approach
if string ab*cd
then we should get ad right by skipping character before * and character after * right?
please advise

1. Whenever you encounter a '*', you remove the last character of the result string
and//what is last character of ab*cd is it d
2. skip the next character of the input string//what is next character...what is input string i guess it is ab*cd
3. Check EVERY character you skip in the input string//...input string ab*cd right?
    If (and only if) that is another '*' then skip an extra character in the input string.
//if it is likestarOut("*str*in*gy") → "ty"     then what is extra character??
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

sure

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {

		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) { //
			if (str.charAt(i) == '*') { // Whenever I encounter a '*'
				result = result.substring(0, result.length() - 1 > 0 ? result.length() - 1 : 0);
				// result = result.substring(0, result.length() - 2 > 0 ?
				// result.length() - 2 : 0);
			} else {
				result = result + str.substring(i, i++); // add each character
			}
		}
		return result;
	}
}

Open in new window


above did not give ab but empty as below
starOut is-->
result = result + str.substring(i, i++); // add each character

Open in new window

What do you think i++ means?
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.2
The value of the postfix increment expression is the value of the variable before the new value is stored.
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {

		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) { //
			if (str.charAt(i) == '*') { // Whenever I encounter a '*'
				result = result.substring(0, result.length() - 1 > 0 ? result.length() - 1 : 0);
				// result = result.substring(0, result.length() - 2 > 0 ?
				// result.length() - 2 : 0);
			} else {
				result = result + str.substring(i, ++i); // add each character
			}
		}
		return result;
	}
}

Open in new window


i see my mistake now i corrected to ++i instead of i++
now i get output as

starOut is-->c

please advise
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {

		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) { //
			System.out.println("str.charAt(i) has *--->"+(str.charAt(i) == '*'));
			if (str.charAt(i) == '*') { // Whenever I encounter a '*'
				result = result.substring(0, result.length() - 1 > 0 ? result.length() - 1 : 0);
				System.out.println("result in if===>"+result);
				// result = result.substring(0, result.length() - 2 > 0 ?
				// result.length() - 2 : 0);
			} else {
				result = result + str.substring(i, ++i); // add each character
				System.out.println("result in else===>"+result);
			}
		}
		return result;
	}
}

Open in new window


above gave below result

str.charAt(i) has *--->false
result in else===>a
str.charAt(i) has *--->true
result in if===>
str.charAt(i) has *--->false
result in else===>c
starOut is-->c

i wonder why only one false came then one true then one false

i thought is should get 2 false then true then two falses
Sorry gudii9,
I asked a question and you don't answer.
You just post the same code over and over again.
This is not working. So from my side I give up.

The answer I wanted you to find for yourself was simply
i++;

Open in new window


I leave you with the complete code I had in mind:
    public static String starOut2(String str) {
        String result = "";
        for (int i = 0; i <= str.length()-1; i++) {
            if (str.charAt(i) == '*') {
                result = result.substring(0, result.length()-1 > 0 ? result.length()-1 : 0);
                i++;
                while (i <= str.length()-1 && str.charAt(i) == '*') {
                    i++;
                }
            } else {
                result = result + str.substring(i, i+1);
            }
        }
        return result;
    }

Open in new window

Avatar of gudii9

ASKER

I asked a question and you don't answer.
You just post the same code over and over again.
This is not working. So from my side I give up.

sorry i tried.

i put i++ in for loop not in while loop as you put.
All the test cases are passing now and i am analyzing your approach and code so that next time my thoughts move quickly in right direction
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {
		/*
		 * String result = ""; for (int i = 0; i <= str.length() - 1; i++) { //
		 * System.out.println("str.charAt(i) has *--->"+(str.charAt(i) == '*'));
		 * if (str.charAt(i) == '*') { // Whenever I encounter a '*' result =
		 * result.substring(0, result.length() - 1 > 0 ? result.length() - 1 :
		 * 0); System.out.println("result in if===>"+result); // result =
		 * result.substring(0, result.length() - 2 > 0 ? // result.length() - 2
		 * : 0); } else { result = result + str.substring(i, ++i); // add each
		 * character System.out.println("result in else===>"+result); } } return
		 * result;
		 */
		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			System.out.println("str.charAt(i) has *--->"
					+ (str.charAt(i) == '*'));
			if (str.charAt(i) == '*') {
				result = result.substring(0,
						result.length() - 1 > 0 ? result.length() - 1 : 0);
				System.out.println("result in if===>" + result);
				i++;
				while (i <= str.length() - 1 && str.charAt(i) == '*') {
					i++;
				}
			} else {
				result = result + str.substring(i, i + 1);
				System.out.println("result in else===>" + result);
			}
		}
		return result;
	}
}

Open in new window


i got required output as below

str.charAt(i) has *--->false
result in else===>a
str.charAt(i) has *--->false
result in else===>ab
str.charAt(i) has *--->true
result in if===>a
str.charAt(i) has *--->false
result in else===>ad
starOut is-->ad
Avatar of gudii9

ASKER

in below if loop


if (str.charAt(i) == '*') {
                        result = result.substring(0,
                                    result.length() - 1 > 0 ? result.length() - 1 : 0);

how i got a?
result.length is 0 right as result=""

why we need two i++ one in while loop  one other in if loop?
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {
		/*
		 * String result = ""; for (int i = 0; i <= str.length() - 1; i++) { //
		 * System.out.println("str.charAt(i) has *--->"+(str.charAt(i) == '*'));
		 * if (str.charAt(i) == '*') { // Whenever I encounter a '*' result =
		 * result.substring(0, result.length() - 1 > 0 ? result.length() - 1 :
		 * 0); System.out.println("result in if===>"+result); // result =
		 * result.substring(0, result.length() - 2 > 0 ? // result.length() - 2
		 * : 0); } else { result = result + str.substring(i, ++i); // add each
		 * character System.out.println("result in else===>"+result); } } return
		 * result;
		 * 
		 * 1. Whenever you encounter a '*', you remove the last character of the
		 * result string and//what is last character of ab*cd is it d 2. skip
		 * the next character of the input string//what is next character...what
		 * is input string i guess it is ab*cd 3. Check EVERY character you skip
		 * in the input string//...input string ab*cd right? If (and only if)
		 * that is another '*' then skip an extra character in the input string.
		 */
		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			System.out.println("str.charAt(i) has *--->"
					+ (str.charAt(i) == '*'));
			if (str.charAt(i) == '*') {
				System.out.println("result.length()--->"+result.length());
				result = result.substring(0,
						result.length() - 1 > 0 ? result.length() - 1 : 0);
				System.out.println("result in if===>" + result);
				i++;
				while (i <= str.length() - 1 && str.charAt(i) == '*') {
					i++;
				}
			} else {
				result = result + str.substring(i, i + 1);
				System.out.println("result in else===>" + result);
			}
		}
		return result;
	}
}

Open in new window


str.charAt(i) has *--->false
result in else===>a
str.charAt(i) has *--->false
result in else===>ab
str.charAt(i) has *--->true
result.length()--->2
result in if===>a
str.charAt(i) has *--->false
result in else===>ad
starOut is-->ad



why above shows result.length() as 2 not 0?
Avatar of gudii9

ASKER

i see due to else loop since first two false for a and then b
Avatar of gudii9

ASKER

      System.out.println("value---->"+result.substring(0,result.length() - 1 >0  );
				result = result.substring(0,
						result.length() - 1 > 0 ? result.length() - 1 : 0);

Open in new window

why above sysout giving compilation error saying

Multiple markers at this line
      - Syntax error, insert ")" to complete Expression
      - The method substring(int, int) in the type String is not applicable for the arguments (int,
       boolean)
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {
		/*
		 * String result = ""; for (int i = 0; i <= str.length() - 1; i++) { //
		 * System.out.println("str.charAt(i) has *--->"+(str.charAt(i) == '*'));
		 * if (str.charAt(i) == '*') { // Whenever I encounter a '*' result =
		 * result.substring(0, result.length() - 1 > 0 ? result.length() - 1 :
		 * 0); System.out.println("result in if===>"+result); // result =
		 * result.substring(0, result.length() - 2 > 0 ? // result.length() - 2
		 * : 0); } else { result = result + str.substring(i, ++i); // add each
		 * character System.out.println("result in else===>"+result); } } return
		 * result;
		 * 
		 * 1. Whenever you encounter a '*', you remove the last character of the
		 * result string and//what is last character of ab*cd is it d 2. skip
		 * the next character of the input string//what is next character...what
		 * is input string i guess it is ab*cd 3. Check EVERY character you skip
		 * in the input string//...input string ab*cd right? If (and only if)
		 * that is another '*' then skip an extra character in the input string.
		 */
		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			System.out.println("str.charAt(i) has *--->"
					+ (str.charAt(i) == '*'));
			if (str.charAt(i) == '*') {
				System.out.println("result.length()--->"+result.length());
      //System.out.println("value---->"+(result.length() - 1 )>0  );
				result = result.substring(0,
						(result.length() - 1 > 0 ? result.length() - 1 : 0));
				System.out.println("result in if===>" + result);
				i++;
				while (i <= str.length() - 1 && str.charAt(i) == '*') {
					i++;
				}
			} else {
				result = result + str.substring(i, i + 1);
				System.out.println("result in else===>" + result);
			}
		}
		return result;
	}
}

Open in new window


i see your point

additional brackets like aove would hae saved many minutes of figuring out at misc operator
http://www.tutorialspoint.com/java/java_basic_operators.htm
public class Test {

   public static void main(String args[]){
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}
This would produce the following result −

Value of b is : 30
Value of b is : 20
Avatar of gudii9

ASKER

i wonder why i++
one in for
other in if loop
another in else loop?
Avatar of gudii9

ASKER

public class StarOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("starOut is-->" + starOut("ab*cd"));
	}

	public static String starOut(String str) {
		/*
		 * String result = ""; for (int i = 0; i <= str.length() - 1; i++) { //
		 * System.out.println("str.charAt(i) has *--->"+(str.charAt(i) == '*'));
		 * if (str.charAt(i) == '*') { // Whenever I encounter a '*' result =
		 * result.substring(0, result.length() - 1 > 0 ? result.length() - 1 :
		 * 0); System.out.println("result in if===>"+result); // result =
		 * result.substring(0, result.length() - 2 > 0 ? // result.length() - 2
		 * : 0); } else { result = result + str.substring(i, ++i); // add each
		 * character System.out.println("result in else===>"+result); } } return
		 * result;
		 * 
		 * 1. Whenever you encounter a '*', you remove the last character of the
		 * result string and//what is last character of ab*cd is it d 2. skip
		 * the next character of the input string//what is next character...what
		 * is input string i guess it is ab*cd 3. Check EVERY character you skip
		 * in the input string//...input string ab*cd right? If (and only if)
		 * that is another '*' then skip an extra character in the input string.
		 */
		String result = "";
		for (int i = 0; i <= str.length() - 1; i++) {
			System.out.println("str.charAt(i) has *--->"
					+ (str.charAt(i) == '*'));
			if (str.charAt(i) == '*') {
				System.out.println("result.length()--->" + result.length());
				// System.out.println("value---->"+(result.length() - 1 )>0 );
				result = result.substring(0,
						(result.length() - 1 > 0 ? result.length() - 1 : 0));
				System.out.println("result in if===>" + result);
				i++;// this is clear as we skip * character
				while (i <= str.length() - 1 && str.charAt(i) == '*') {// what
																		// is
																		// purpose
																		// of
																		// this
																		// while?
					i++;// why we need to increment here?
				}
			} else {
				result = result + str.substring(i, i + 1);// this clear if false
															// result becomes a
															// then ab etc
				System.out.println("result in else===>" + result);
			}
		}
		return result;
	}
}

Open in new window


main questions are as above
i wonder why i++
one in for
other in if loop
another in else loop?
Remove one of them and "see" what happens.
*See = debug step by step or add System.out.println()
Avatar of gudii9

ASKER

sure
Avatar of gudii9

ASKER

but we are using all flow cocntrol statements like for, if, while, else everything here which i like