Unusual stringWithFormat: argument - ios

I apologize if this is a noob question.
I have been following this tutorial about mapkit and I stumbled on this line of code
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
The reason this is unusual at least to me is that it is missing the nsstring that has the %# flags in it. The tutorial claims that we are adding the latitude and longitude information into the json.
But when I print out formatString and json, the output is identical.
I have never seen nsstrings used in this way before. Is there a hidden variable that is getting set?
Can someone explain to me how this nsstring object (named json) contains those 4 arguments?

Someplace else in the code, formatString must be defined something like this:
NSString *formatString = #"latitude=%f, longitude=%f, %f = half the number of meters in a mile";
Make sure your test looks like this:
NSLog(#"the format is %# and the json is %#", formatString, json);
They shouldn't look the same. The only way they would look the same is if format string doesn't refer to any format specifiers, like this:
NSString *formatString = #"I'm a silly format with no percent format specifiers";
Here's a good intro on the topic from Apple.

That formatString actually contains the %#'s. It might be like this:
NSString *formatString = #"lat: %f | lon: %f | half-meters-per-mile: %f";
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
(note that the substitutions (%f) might not be correct, I'm guessing)
As for how it contains those four arguments, everything after the first one are values that you want added into the string. The first one is a string that says where to put those values.

If you check the tutorial, following line of code is written above what you have posted-
NSString *jsonFile = [[NSBundle mainBundle] pathForResource:#"command" ofType:#"json"];
NSString *formatString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];
From here the format string is created, this file will be available in the resources folder of your tutorial.

Related

Separate a string into different Array

I have a string coming from server , i want to show some part of string in a view and rest part of string in other view .
Thanks for help.
i want to get the last word of last line of first view. i have searched ,but nothing seems to help me. If any one can suggest me something i would be glad to him/her.
NSString *fromIndex = [_categoryWiseNews.article substringWithRange:NSMakeRange(0, lastWordOfFirstView)];
i have tried with substringWithRange but with this you have to know the lastWordOfFirstView index number for breaking the string into two parts, for which i have no idea.
I really don't know what it is that you're asking lastWordOfFirstView might make sense to you because it is relevant to the thing you are working on. But to us it means nothing.
You can separate a string into words in an array doing this...
NSString *string = #"Hello world, this is a string";
NSArray *array = [string componentsSeparatedByString:#" "];
// array is now... [#"Hello", #"world,", #"this", #"is", #"a", #"string"];
Then you can get the last word from it...
NSString *lastWord = [array lastObject];
Use this to get the last word from a sentence:
NSString *lastWord = [[fullSentenceString componentsSeparatedByString:#" "] lastObject];

Adding a percentage % sign to an NSString [duplicate]

I want to have a percentage sign in my string after a digit. Something like this: 75%.
How can I have this done? I tried:
[NSString stringWithFormat:#"%d\%", someDigit];
But it didn't work for me.
The code for percent sign in NSString format is %%. This is also true for NSLog() and printf() formats.
The escape code for a percent sign is "%%", so your code would look like this
[NSString stringWithFormat:#"%d%%", someDigit];
Also, all the other format specifiers can be found at Conceptual Strings Articles
If that helps in some cases, it is possible to use the unicode character:
NSLog(#"Test percentage \uFF05");
The accepted answer doesn't work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character '\uFF05' only work for this.
So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \uFF05.
seems if %% followed with a %#, the NSString will go to some strange codes
try this and this worked for me
NSString *str = [NSString stringWithFormat:#"%#%#%#", #"%%",
[textfield text], #"%%"];
uese following code.
NSString *searchText = #"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:#"%%%#%%",searchText];
will output: %Bhupi%
iOS 9.2.1, Xcode 7.2.1, ARC enabled
You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [stringTest stringByAppendingString:#"%"];
NSLog(#"%#", stringTest);
For iOS7.0+
To expand the answer to other characters that might cause you conflict you may choose to use:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
Written out step by step it looks like this:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [[stringTest stringByAppendingString:#"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(#"percent value of test: %#", stringTest);
Or short hand:
NSLog(#"percent value of test: %#", [[[[NSString stringWithFormat:#"%d", test]
stringByAppendingString:#"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
Thanks to all the original contributors. Hope this helps. Cheers!

Objective C Array Count String Issue

Okay I am new to objective C and am trying hard to learn it on my own with out bother the stacked overflow community to much but it is really quite different then what I'm used to (C++).
But I have come across a issue that I for the life of me can't figure out and I'm sure it's going be something stupid. But I am pulling questions and answers from a website that then will display on my iOS application by using this code.
NSString * GetUrl = [NSString stringWithFormat:#"http://www.mywebpage.com/page.php"];
NSString * GetAllHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:GetUrl] encoding:1 error:nil];
NSString *PullWholeQuestion = [[GetAllHtml componentsSeparatedByString:#"<tr>"] objectAtIndex:1];
NSString *FinishWholeQuestion = [[PullWholeQuestion componentsSeparatedByString:#"</tr>"] objectAtIndex:0];
After I get all of the webpage information I strip down each question and want to make it where it will do a loop process to pull the questions so basically I need to count how many array options there are for the FinishedWholeQuestion variable
I found this snippet online that seemed to work with there example but I cant repeat it
NSArray *stringArray = [NSArray arrayWithObjects:#"1", #"2", nil];
NSLog(#"count = %d", [stringArray count]);
"componentsSeparatedByString" returns an NSArray object, not a single NSString.
An array object can contain zero, one or more NSString objects, depending on the input.
If you change "FinishWholeQuestion" into a NSArray object, you'll likely get a few components (separate by a string).
And now that I'm looking at your code a little more closely, I see you're making an assumption that your array is always valid (and has more than 2 entries, as evidenced by the "objectAtIndex: 1" bit).
You should also change the first character of all your Objective-C variables. Best practices in Objective-C are that the first character of variables should always be lower case.
Like this:
NSString * getUrl = [NSString stringWithFormat:#"http://www.mywebpage.com/page.php"];
NSString * getAllHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:getUrl] encoding: NSUTF8StringEncoding error:nil];
NSArray * allQuestions = [getAllHtml componentsSeparatedByString:#"<tr>"];
if([allQuestions count] > 1)
{
// assuming there is at least two entries in this array
NSString * pullWholeQuestion = [allQuestions objectAtIndex: 1];
if(pullWholeQuestion)
{
NSString *finishWholeQuestion = [[pullWholeQuestion componentsSeparatedByString:#"</tr>"] objectAtIndex:0];
}
}

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).

Convert float to NSString using custom format? ("xx:yy")

I'm getting a JSON string back from a web service I'm using, one of the items is a float, which is formatted like this: "1.2".
But I actually want to make it show like a time number, so like this: "01:20".
What would be the easiest way of doing this?
I thought about converting the float to a string and then splitting it into 2 pieces
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
NSArray *tmpArr = [timeValue componentsSeparatedByString:#"."];
NSString *tmpFirst = (NSString *)[tmpArr objectAtIndex:0];
NSString *tmpSecond = (NSString *)[tmpArr objectAtIndex:0];
But somehow when I convert it, it returns me a negative number
NSLog(#"timeValue: %#", timeValue);
timeValue: -1.99
I think the problem is in this line.
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
I think timeValue is of type NSString if not then why are you using same variable twice.
It should be like
timeValueString = [NSString stringWithFormat:#"%.2f", timeValueFloat];

Resources