-2
    String str="a*nice*day";
    String res="";

    int j=0;

    for(int i=0;i<str.length();i++)
    {
        if(str.charAt(i)=='*')
        {
            j=i++;
            break;
        }

    }
    while(str.charAt(j)!='*')
    {
        res=res+str.charAt(j);
        j++;
    }


    System.out.println(res);

Here i'm trying to extract the word "nice" without using substring method...and whats wrong with this program?

Balaji
  • 1,773
  • 1
  • 17
  • 30
  • 1
    Remember to always show what your actual output and/or error messages look like. – domsson Jul 03 '17 at 13:03
  • 1
    Hint, your `while` loop will break immediately, because the first `str.charAt(j)` is guaranteed to be a `'*'` (reason: `j=i++;` doesn't do what you seem to think it does) – UnholySheep Jul 03 '17 at 13:04
  • `j=i++;` will set j to the value of i and only then increment i. See: https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java – OH GOD SPIDERS Jul 03 '17 at 13:06
  • change ` j=i++;` to ` j=i+1;` or ` j=++i;` – Eritrean Jul 03 '17 at 13:07

2 Answers2

0

Try this code. I think your problem was with i++

String str="a*nice*day";
String res="";

int j=0;

for(int i=0; i<str.length(); i++){

      if(str.charAt(i)=='*'){
            j = i + 1;
            break;
        }
    }

while(str.charAt(j) != '*'){
    res=res+str.charAt(j);
    j++;
}

System.out.println(res);
sf_
  • 1,138
  • 2
  • 13
  • 28
0

j = i++; should be j = ++i;

Otherwise you assign i to j as i++ is a post increment. With post increment, the value of i is changed only after this statement.

And you are stuck to the index of the * char found and not the index of the next char as you want to.

davidxxx
  • 125,838
  • 23
  • 214
  • 215