Link to home
Start Free TrialLog in
Avatar of danBosh
danBoshFlag for United Kingdom of Great Britain and Northern Ireland

asked on

String manipulation

Say i have a string representing a url such as:

String myUrl = "http://kpldb:8083/hartlepool/communityPortalHome/content/councilGateway/?view=Standard$a=5441"

What it the best and most cost effective way of taking the string and changing 'view=Standard' to 'view=TextOnly', bearing in mind the string will not always be the same length and $a=5441 will not always be on the ene
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Something like:

            String myUrl = "http://kpldb:8083/hartlepool/communityPortalHome/content/councilGateway/?view=Standard$a=5441";
            final String TARGET = "view=Standard";
            final String NEW = "view=TextOnly";
            int start = -1;

            if ((start = myUrl.indexOf(TARGET)) > -1) {
                  StringBuffer sb = new StringBuffer(myUrl);
                  sb.delete(start, start + TARGET.length());
                  sb.insert(start, NEW);
                  System.out.println(sb.toString());
            }
ASKER CERTIFIED SOLUTION
Avatar of Venabili
Venabili
Flag of Bulgaria 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
Avatar of jimmack
jimmack

Venabili is almost right ;-)  It's replaceAll(), not replace() ;-)

If you are using 1.4, you could do the following:

        String orig = "http://kpldb:8083/hartlepool/communityPortalHome/content/councilGateway/?view=Standard$a=5441";
        String replaced = orig.replaceAll("view=Standard", "view=TextOnly");
:) Agree
Possible problems with those approaches is if the String contains the text 'view=Standard' elsewhere in the url. If it is possible that this is the case then you'll need to parse the URL to perform the replacement. Let me know if this is the case and I'll show you a bullet proff approach.
>>
Possible problems with those approaches is if the String contains the text 'view=Standard' elsewhere in the url.
>>

No with my approach ;-)
No=Not ;-)
Avatar of danBosh

ASKER

sorry CEHJ i ment to accept your answer, i made a school boy error
Don't worry. Repetition is not an issue anyway:

1. it can't be included before the query string
2. if it occurs more than once in the query string it'll be ignored by the server after the first occurrence anyway
> No with my approach ;-)

Yes it can have problems.
replaceFirst() is another alternative (aside from the fact that the point is now moot anyway ;-))
>>now moot

now academic surely? ;-)
Indeed :-P

;-)