0

A school assignment has tasked me with replacing all instances of one String (in this case "_") with alternating Strings (in this case, alternating between < I > and < /I >).

NOTE: The method immediately returns the original String if there is an odd number of "_"s.

Here is what I have tried already, it always prints out the original string:

public String convertItalics ()
{ 
    String temp = line;

    if(temp.length() - temp.replace("_", "").length() % 2 == 0)
    {
        temp = line;

        while(temp.contains("_"))
        {
            temp.replace("_", "<I>");
            temp.replace("_", "</I>");
        }
    }
    return temp;
}

Any help that you could give would be greatly appreciated.

Alex
  • 1
  • Shit! Closed while I elaborated on the answer. The temp.replace replaces all matches but doesn't modify temp in place, so you have to use `temp=temp.replaceFirst (...)`. And the if makes wrong assumptions about operator precedence (minus before modulo). Try `if (temp.replaceAll ("[^_]", "").length () % 2 == 0)` – user unknown Apr 25 '18 at 01:02
  • Why not use a for loop and iterate over each character. Then every time you find a char matching '_' you can set a local flag to determine how to replace each one. – billy.mccarthy Apr 25 '18 at 01:27

0 Answers0