Something goes wrong when I convert NSString to float - ios

Something goes wrong when I convert NSString to float. I got zero value, but why?
NSString *polylineStr = #"51.351305,-0.024239;51.374855,-0.092412";
NSArray *strPolylineArr = [polylineStr componentsSeparatedByString:#";"];
for ( NSString *str in strPolylineArr) {
NSArray *arr = [str componentsSeparatedByString:#","];
NSString *firstString = [arr firstObject];
NSLog(#"__str %# float %f", [arr firstObject], [firstString floatValue]);
}
my output is
__str 51.351305 float 0.000000
__str 51.374855 float 51.374855
I found that something wrong with first string.

HI in your string some character add : '' you can't see but copy character which is on single quote or use below code:
NSString *polylineStr = [NSString stringWithFormat:#"51.351305,-0.024239;51.374855,-0.092412"];
NSArray *strPolylineArr = [polylineStr componentsSeparatedByString:#";"];
for ( NSString *str in strPolylineArr) {
NSArray *arr = [str componentsSeparatedByString:#","];
NSString *firstString = [arr firstObject];
NSLog(#"__str %# float %f", [arr firstObject], [firstString floatValue]);
}

Related

Scan for numbers in Objective - C

I wonder how could I able to find all the numbers as follows.
Input
NSString* input = # "1m3s"
The desired output
#[#"1" #"3"]
I have tried the following approach
NSArray *arr = [input componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"ms"]];
it returned me
#[#"1",#"3",#"#"]
Is there a better approach to solve this problem, any suggestion?
Even though this question has been marked as a duplication, I have tested the following answer but did not work.
Update
That could be any string value.
if input is #"11m32s" or #11m32 and then desired output would be #[#"11", #"32"];
if input is #"11x32" or #11x32y and then desired output would be #[#"11", #"32"];
Using a NSScanner would allow you to scan floats as well. In addition your array is populated directly with NSNumber instead of NSString.
NSString * input = # "12m32s";
NSScanner * aScanner = [NSScanner scannerWithString:input];
NSInteger aInt;
NSMutableArray * result = [NSMutableArray array];
while (!aScanner.isAtEnd)
{
if ([aScanner scanInteger:&aInt])
{
[result addObject:#(aInt)];
}
if (!aScanner.isAtEnd)
{
aScanner.scanLocation += 1;
}
}
NSLog(#"%#",result);
Try:
NSString* input = # "1m3s";
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSArray *outArray = [input componentsSeparatedByCharactersInSet:nonDigitCharacterSet];
outArray = [outArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
To extract numbers you can use Regular Expression.
NSString* input = # "1m3s";
NSString *pattern = #"\\d+"; // searches for one or more digits
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
[result addObject: [input substringWithRange:match.range]];
}
NSLog(#"%#", result);
Or if you want to be more specific and extract the numbers in an expression ##m##s use
NSString* input = # "1m3s";
NSString *pattern = #"(\\d+)m(\\d+)s";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:input options:0 range:NSMakeRange(0, input.length)];
if (match) {
NSArray *result = #[[input substringWithRange:[match rangeAtIndex:1]], [input substringWithRange:[match rangeAtIndex:2]]];
NSLog(#"%#", result);
}
I think's it's helpful for you below the code work for me.
NSString *originalString = #"1m3s";
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i=0; i<[originalString length]; i++) {
if (isdigit([originalString characterAtIndex:i])) {
NSMutableString *strippedString = [NSMutableString stringWithCapacity:10];
[strippedString appendFormat:#"%c",[originalString characterAtIndex:i]];
[arr addObject:strippedString];
}
}
NSLog(#"%#",arr.description);
Use below code :
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSArray *outArray = [[input componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:#""];
Use this handy approach:
+ (NSArray *)extractNumberFromText:(NSString *)text
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSMutableArray *numberArray = [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet]mutableCopy];
[numberArray removeObject:#""];
return numberArray;
}
Here is code to get your desire output:
NSString* input = #"1m3s";
NSString *newString = [[input componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < [newString length]; i++) {
NSString *ch = [newString substringWithRange:NSMakeRange(i, 1)];
[array addObject:ch];
}
NSLog(#"%#",array.description);
You can also use this code bellow.
NSString * String = #"24fsd35rf";
NSArray* Array = [String componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSLog(#"%#",[Array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self <> ''"]]);

How to split a string from UITextField

I have a UITextField as following:
_itemTextField = [[UITextField alloc];
This UITextField may contain item number only ex: "11321" or item number and size ex: "11321-XS" or "12355-40".
I want to extract the item and size (if it's available) separately in two different variables, as following:
NSString *itemNumber = #"11321";
NSString *itemSize = #"XS";
Please advise.
NSString *str = #"11115-ex";
if([str containsString:#"-"]){
NSArray * arr =[str componentsSeparatedByString:#"-"];
NSString *first = [arr objectAtIndex:0];
NSString *second = [arr objectAtIndex:1];
NSLog(#"Return String %# %#",first,second);
}
else
{
NSLog(#"Return String %#",str);
}

Loading text from .txt file iOS

I've been trying to convert a Quiz app that was based for Mac OS to iOS because I liked the idea of loading all questions from a single .txt file.
I'm still pretty new in the Objective-C language as I've used C# before.
The questions and answers are loaded via this function:
- (void)loadQuestionsAndAnswersArray {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA) {
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++) {
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound) {
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
}
The app then has a text field for the question and then 3 buttons, one for each answer. And when a new questions appears it changes the text within the text field and the title of the buttons.
This code works like a charm on the Mac App but on the iOS version it's like it can't find the txt file, the buttons etc is left blank.
I've been sitting on this for a week or so about now and that's the reason for this post.
The iOS app is based on this Github Mac app: https://github.com/SquaredTiki/Quizzer
If you want to have a look at how I've tried to convert the app here's a link to that to:
https://www.dropbox.com/s/1jqz9ue97p3v2h1/iTrafikk.zip?dl=0
And of course I'm not asking you to solve the whole issue for me, maybe just push me in the right direction if possible :)
I checked your project. And it seems that you are not calling loadQuestionsAndAnswersArray anywhere in your code. Also you are not initializing the questionsAndAnswers anywhere in the project.
Change your code like:
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadQuestionsAndAnswersArray];
}
- (void)loadQuestionsAndAnswersArray
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA)
{
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++)
{
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound)
{
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
if (!questionsAndAnswers)
{
questionsAndAnswers = [[NSMutableArray alloc] init];
}
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
[self loadQuestionsAndAnswersIntoInterface];
}

NSString to char my[16]

I am having NSString like :
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
how can i convert it to char array as shown below:
char keyPtr[16] = {225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45}
can anyone help!
Thanks
NSString *input = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
char output[16];
NSArray *elements = [input componentsSeparatedByString:#","];
NSAssert([elements count] == 16, #"Input has wrong number of elements");
unsigned index = 0;
for (NSString *element in elements) {
int value = [element intValue];
NSAssert(value >= 0 && value <= 255, #"Element is invalid");
output[index++] = (char)value;
}
Note: You probably should be using a int[], and not char[], for output.
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
NSArray *array = [str componentsSeparatedByString:#","];
Then use this in a for loop or something to add to your char array:
char* myLilChar = [[array objectAtIndex:i] UTF8String];
Cheers :)
If you want to be as you said, use below
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
NSArray *array = [str componentsSeparatedByString:#","];
unsigned char keyPtr[array.count];
for(int i=0;i<array.count;i++)
keyPtr[i] = (unsigned char)[[array objectAtIndex:i] intValue];

Parse a NSDictionary

I have a NSDictionary looks like this:
data = {
start = {
name = "abc";
age = "123";
id = AA838DDE;
};
};
how can I parser the dictionary to get individual name, age, and id? Thanks.
NSString *name = dictionary[#"data"][#"start"][#"name"];
I add an other answer because I hate the new Objective-C syntax (sorry #Raphael Olivieira)
NSString *name = [[[[dictionary objectForKey:#"data"] objectForKey:#"start"] objectAtIndex:0] objectForKey:#"name"];
NSLog(#"%#", name);
Longer than the previous answer but you know what you do and you don't code in C.
BTW, using the other syntax :
NSString *name = dictionary[#"data"][#"start"][0][#"name"];
NSLog(#"%#", name);
why don't you simply try:
int arrCount = [[[dictionaryObject valueForKey:#"data"] objectForKey:#"start"] count];
for(int i = 0 ; i < arrCount ; i++)
{
NSString *strName = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"name"];
NSString *strAge = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"age"];
NSString *strID = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"id"];
NSLog(#"%# - %# - %#", strName, strAge, strID);
}

Resources