Search code examples
javastringsubstringoverwrite

Getting String and return the same string with "+" before every"-"


I get a String and I need to return with "+" before every "-"in it for example for the String= "5x^6+3x-8x^2-8x^3" it should return:5x^6+3x+-8x^2+-8x^3

        String p="-5.0x^4-1.0x^3-3.0x^2-2.0"
        String temp=p;
        for(int i = 1;i<p.length();i++) {
            int start=0;
            if(p.charAt(i)=='-') {
                temp =temp.substring(start,i);
                temp+="+";
                temp+=p.substring(i+1,p.length());//here it over writes
                start=i;
            }
        }
        

it switches the "-" with "+" the return: -5.0x^4+1.0x^3+3.0x^2+2.0


Solution

  • Instead of concatentating substrings, I would use a StringBuilder. Iterate the contents. On - insert a +. Like,

    String p = "5x^6+3x-8x^2-8x^3";
    StringBuilder sb = new StringBuilder(p);
    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == '-') {
            sb.insert(i, '+');
            i++;
        }
    }
    p = sb.toString();
    

    Results in (as requested)

    5x^6+3x+-8x^2+-8x^3