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
danBoshAsked:
Who is Participating?
 
VenabiliCommented:
What JDK do you use? If 1.4 you can use replace.
0
 
CEHJCommented:
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());
            }
0
 
jimmackCommented:
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");
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
VenabiliCommented:
:) Agree
0
 
objectsCommented:
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.
0
 
CEHJCommented:
>>
Possible problems with those approaches is if the String contains the text 'view=Standard' elsewhere in the url.
>>

No with my approach ;-)
0
 
CEHJCommented:
No=Not ;-)
0
 
danBoshAuthor Commented:
sorry CEHJ i ment to accept your answer, i made a school boy error
0
 
CEHJCommented:
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
0
 
objectsCommented:
> No with my approach ;-)

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

now academic surely? ;-)
0
 
jimmackCommented:
Indeed :-P

;-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.