Reputation: 452
What I am looking to do is use placeholders in a string and replace the placeholders with data specific to the user. I can setup the placeholders to be anything so basically I am looking to do the following:
Here is what I have. I currently have a url that has a set of placeholders like so. http://example.com/resource?placeholder1=placeholder2 or http://placeholder1:[email protected]/something?placeholder3
How do I properly label the placeholders and replace them?
Thank you in advance for any help.
Upvotes: 1
Views: 1148
Reputation: 726
This might help you.
#define placeHolder1 @"<>p1p1p1<>"
#define placeHolder2 @"<>p2p2p2<>"
And place this in a function of yours where you want to replace strings
NSString * string = [NSString stringWithFormat:@"http://example.com/resource?%@=%@",placeHolder1,placeHolder2];
NSLog(@"string %@",string);
NSString * replacerForP1 = @"123";
NSString * replacerForP2 = @"741";
string = [string stringByReplacingOccurrencesOfString:placeHolder1
withString:replacerForP1];
string = [string stringByReplacingOccurrencesOfString:placeHolder2
withString:replacerForP2];
NSLog(@"string %@",string);
It would be best to keep your placeholder strings in the constants defined somewhere. And ofcourse the replacement of those placeholders will be dynamic as you said so cannot make them constants.
Tell me if this helps or if you require further assistance in the matter.
Upvotes: 0
Reputation: 7903
Quote : "I want to replace placeholder1 with an NSString I have already created called value1 and placeholder2 with an NSString called key1."
NSString *mainUrl = "http://example.com/resource";
NSString *string1 = "value1";
NSString *string2 = "value2";
Now change your URL:
NSString *newURL = [NSString NSStringWithFormat:@"%@?%@=%@",mainUrl,string1,string2];
This will generate newURL
: http://example.com/resource?value1=value2
Upvotes: 0
Reputation: 546
You can use the stringByReplacingOccurrencesOfString method as below
NSString *strUrl = @"http://example.com/resource?placeholder1=placeholder2";
strUrl = [strUrl stringByReplacingOccurrencesOfString:@"placeholder1" withString:@"value1"];
strUrl = [strUrl stringByReplacingOccurrencesOfString:@"placeholder2" withString:@"key1"];
Upvotes: 3