0

i have a String NSString *const kAUrl = @"http://www.google/start.php?show=best&usr=(here)&pwd=x";

and

i want to pass another String NSString *a = @"aa";

to above url at the place i have written (here) in above url.

How can i pass it?

regards.

2
  • Why are you creating a string constant that you are then trying to modify? Commented Nov 17, 2010 at 13:17
  • I can't see the value of making an NSString constant, when it is already immutable? Commented Nov 17, 2010 at 13:26

4 Answers 4

3

You will need to encode the string suitable for URL using the NSString instance method -[stringByAddingPercentEscapesUsingEncoding:].

Then place into the URL using -[stringWithFormat:].

For example:

-(NSURL*)showBestURLWithUser:(NSString*)user {
{
   user = [user stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
   static NSString* template = @"http://www.google/start.php?show=best&usr=%@&pwd=x";
   NSString* urlString = [NSString stringWithFormat:template, user];
   return [NSURL URLWithString:urlString];
}
Sign up to request clarification or add additional context in comments.

4 Comments

is there a reason for using const? the string is immutable in this state (without assigning a new object reference to it), as it is not a NSMutableString...
As far as I know, a const NSString* object you will not be able to re-assign a new NSString, and will only take a constant string (ie, @"string").
suggest me plz. i need const.
@shishir.bobby: I extended the example to use a constant string for the URL template, and framed it in a proper method context.
3

Use NSString stringWithFormat:

NSString *a = @"hello";
NSString *kAUrl = [NSString stringWithFormat:@"http://www.google/start.php?show=best&usr=%@&pwd=x", a];

kAUrl now contains the contents of a where the %@ was.


Watch out though - if a contains any URL reserved characters (i.e. an & etc) it might break your url.

2 Comments

its wont work, since NSString *const a ; a is const..it giving me error.plz suggest.
Why must it be a const? Just don't make it a const and you should be fine.
1

You would change your declaration to this:

NSString *kAUrl = [NSString stringWithFormat:@"http://www.google/start.php?show=best&usr=%@&pwd=x", a];

Good Luck!

Comments

1

NSString *a = @"aa";

NSString *kAUrl = [NSString stringWithFormat:@"http://www.google/start.php?show=best&usr=%@&pwd=x",a];

kAUrl = [kAUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

job done.

2 Comments

wouldn't this encode the entire string as a URL? including URL protocol, etc portion?
why do you need the "const"??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.