Replace multiple placeholders in string - ios

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:
Setup placeholders in a string (up to 4 placeholders)
Replace those placeholders with strings I specify
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:placeholder2#example.com/something?placeholder3
How do I properly label the placeholders and replace them?
Thank you in advance for any help.

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"];

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

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.

Related

Concatenate two strings with a backslash iOS

I am new to Objective-C and I need to have a string like "abc\123"
To have this I have tried doing:-
NSString *first = #"abc\\"; //Should escape
NSString *second= #"123";
NSString *combined= [NSString stringWithFormat:#"%#%#", first, second]; //which should give abc\123
But I get an output as "abc\\123".
I am really stuck on this one. Any help is appreciated
Backslash itself is the escape character so needs character to read ahead, you need to escape it.
This results same output you like.
NSString *first = #"abc\\";
You can check just by adding one more backshash #"abc\\\" gives you missing character "" runtime error.
NSString *first = #"abc\\"; // log results abc\
NSString *first = #"abc\\\\"; // log results abc\\
Can do by adding between format specifiers by following same backslash rule.
NSString *combined= [NSString stringWithFormat:#"%#\\%#", first, second];
It's the output issue, in fact, the string is correct.
let array = ["abc", "123"]
let separator = "\\"
separator.characters.count //count=1
let x = array.joined(separator: "\\")
x.characters.count //count = 7
You can use
stringByReplacingOccurrencesOfString:withString:
So in your case
NSString *first = #"abc\\"; //Should escape
NSString *second= #"123";
NSString *first = [first stringByReplacingOccurrencesOfString:#"\\" withString:#"\"];
NSString *combined= [NSString stringWithFormat:#"%#%#", first, second];
So your result will be abc\123

Replacing value with string in objective c

i want to replace the value of placemark.name with the string MyPostition in a textfield station but this lines of code doesn't work any suggestions please
_station.text = [NSString stringWithFormat:#"%#",placemark.name];
_station.text=[NSString stringWithFormat:#"%#",#"MyPosition"];
If MyPosition is a variable from which you want to set the value then please remove the " from this variable as follows:
_station.text=[NSString stringWithFormat:#"%#",MyPosition];
Update as understood by your requirement:
_station.text = [NSString stringWithFormat:#"%#",placemark.locality];
Please try this code. Its may be useful to you
NSString *str = #"This is a MyPosition";
str = [str stringByReplacingOccurrencesOfString:#"MyPosition"
withString:#"duck"];
Use this format:
_station.text = [NSString stringWithFormat:#"%#",placemark.locality];

iOS: Create String from Variable and string combined

I need to concatenate a string and a variable together - I kind of find lots of examples of adding a string prior to a variable but not the other way round - how do I do this?
NSString *theImage = [[self.detailItem valueForKey:#" resimagefiletitle"] description], #"'add on the end";
Something like this:
NSString *theImage = [NSString stringWithFormat:#"%# %#",[self.detailItem valueForKey:#" resimagefiletitle"], #"'add on the end"];
Or:
NSString *theImage = [NSString stringWithFormat:#"%# add on the end",[self.detailItem valueForKey:#" resimagefiletitle"]];
Try this
NSString *theImage = [NSString stringWithFormat:#"%# '>",[[self.detailItem valueForKey:#"resimagefiletitle"] description]];
Here I am considering [[self.detailItem valueForKey:#"resimagefiletitle"] description] gives NSString
We can concat diffrent type of datatypes into string by mention the format for it.
like if your want to concat two or more strings together then you can use the following code:
NSString *NewString = [NSString stringWithFormat:#"%#%#",#"This Is",#"way to concate string"];
and if your want concat integer value then you can mention the data format for it "%i".
eg:
int OutOf = 150;
NSString *NewString = [NSString stringWithFormat:#"%#%i",#"I got 100 out of ",OutOf];
this may help you.

NSString concatenate on creation

I'm trying to concatenate 2 strings assigning the result to a new string.
Normally I would do this way:
NSString * s = [NSString stringWithFormat: #"%#%#", str1, str2];
Now I wish s to be static
static NSString * s = [NSString stringWithFormat: #"%#%#", str1, str2];
but compiler kick me with "Initializer element is not a compile-time..."
Is there any way to do this? I Googled a bit with no results and also I have not found answers on StackOverflow asking the question.
And what about using a short form like (in PHP)
$s = $str1.$str2;
Any help will be appreciated.
EDIT: What i want to achieve is to have a config file like this (in PHP code)
define ("BASE_URL", "mysite.com/");
define ("SERVICE_URL1", BASE_URL."myservice1.php?param1=value1");
define ("SERVICE_URL2", BASE_URL."myservice2.php?param2=value2");
I prefer to have all configurations strings in 1 file and i found usefull static strings in objective c. Just want to put 2 usefull thing together :)
EDIT2: There's no metter if i obtain this with defines, but the NSString way is preferred and i use static just beacause const make me some compilation problems i haven't solved yet
Use this code for creating static s:
static NSString * s = nil;
if (!s)
s = [NSString stringWithFormat: #"%#%#", str1, str2];
Also for concatenating two string you case use such code: NSString *s = [str1 stringByAppendingString: str2];
UPDATED:
You can concat static string by putting them one by one.
Example:
#define STR1 #"First part" #" Second part"
#define STR2 #"Third part " STR1
NSLog(#"%#", STR2);
This cole will print Third part First part Second part
I think below lines may help:
NSString *str1 = #"String1";
NSString *str2 = #"String2";
NSString *combinedStr = [str1 stringByAppendingString:str2];
If you can use a define, it is pretty simple:
#define A #"a"
#define B #"b"
…
static NSString *ab = A B; // or: #"A" #"B"
You can always concatenate string literals with a single space.
But something very important has to happen to use defines. What's wrong with computing it non-static or compute it once?
BTW: You should use dispatch_once() and not if. For the reasons you can search "dispatch_once" on SO.
If you don't mind compiling Objective-C++ code, you could simply change the extension from .m to .mm, by default XCode compiles according to file type, and this is valid in Objective-C++
Solved this way:
#define kBaseURL #"mysite.com/"
static NSString *kServiceUrl1 = kBaseURL #"myservice1.php?param1=value1";
static NSString *kServiceUrl2 = kBaseURL #"myservice2.php?param2=value2";
thanks all.
now the question is
wich one i have to accept as right answer? I mean, mine is the solution, but I would never have got there without your help guys

iOS finding string within a string

Hello everyone I am trying find a string inside a string
lets say I have a string:
word1/word2/word3
I want to find the word from the end of the string to the last "/"
so what I will get from that string is:
Word3
How do I do that?
Thanks!
You are looking for the componentsSeparatedByString: method
NSString *originalString = #"word1/word2/word3";
NSArray *separatedArray = [originalString componentsSeparatedByString:#"/"];
NSString *lastObject = [separatedArray lastObject]; //word3
once check this one By using this one you'l get last pathcomponent values,
NSString* theFileName = #"how /are / you ";
NSString *str1=[theFileName lastPathComponent];
NSLog(#"%#",str1);
By using lastPathComponent you'l get the last path component directly no need to take array for separate the string.
you must use NSScanner class to split substring.
check this.
Objective C: How to extract part of a String (e.g. start with '#')
NSString *string = #"word1/word2/word3"
NSArray *arr = [string componentsSeperatedByString:#"/"];
NSSting *str = [arr lastObject];
You can find it also with this way:
NSMutableString *string=[NSMutableString stringWithString:#"word1/word2/word3"];
NSRange range=[string rangeOfString:#"/" options:NSBackwardsSearch];
NSString *subString=[string substringFromIndex:range.location+1];
NSRegularExpression or NSString rangeOfString:options:range:locale: (with options to search backwards).
The answer really depends on exactly what the input string will contain (how consistent it is).

Resources