Compare char array with string in iOS program [duplicate] - objective-c

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to compare char* and NSString?
If I have:
char XYZ[256]="";
how can I compare this char array with another string (e.g. "testing") in an iOS Objective-C program?

Use strcmp
char XYZ[256] = "";
char *string = "some other string";
int order = strcmp(XYZ, string);
RETURN VALUES
The strcmp() and strncmp() functions return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that \200' is greater than\0'.

You can also convert them up to NSString, this makes a lot overhead, but brings your string to Objective-C object:
char XYZ[256] = "";
NSString *s = [[NSString alloc] initWithBytes:XYZ length:strlen(XYZ) encoding:[NSString defaultCStringEncoding]];
NSString *testing = #"testing";
if ([testing compare:s] == NSOrderedSame) {
NSLog(#"They are hte same!");
}
Note that strcmp is A LOT faster!

Just because it is iOS doesnt mean that you cannot "#include" string.h and use "strcmp" (now as stated above).
The alternative would be to create a new NSString and compare it using a comperable iOS Objective-C call:
NSString myString = [NSString stringWithCString:XYZ encodingNSASCIIStringEncoding];
if(YES == [myString isEqualToString:#"testing"]){
// Perform Code if the strings are equal
}else{
// Perform Code if the strings are NOT equal
}

Related

How to Localize NSString with format [duplicate]

This question already has an answer here:
iOS: How to localize strings with multiple interpolated parameters?
(1 answer)
Closed 5 years ago.
How to localize the NSString with format.
int value = 20;
NSString *str = #"hello";
textLabel.text = [NSString stringWithFormat:#"%d %#", value, str];
I tried
textLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%d %#", #"%d %#"), value, str];
but didn't work. Any help is appreciated.
Your localized string itself must be a format pattern:
"ValueAndStringFMT" = "Value %1$d and string %2$#";
And in your code:
textLabel.text = [NSString
stringWithFormat:NSLocalizedString(#"ValueAndStringFMT"),
value, str
];
Why %1$d and not just %d? So you can change the order. E.g. in some language you may like to have the order swapped:
"ValueAndStringFMT" = "Cadena %2$# y valor %1$d";
Of course, that is somewhat dangerous as if someone uses more placeholders than your string call offers or uses the wrong types, your app may crash. If you want to be safe, you do a search an replace instead:
"ValueAndStringFMT" = "Value [[VALUE]] and string [[STRING]]";
And in your code:
NSString * string = NSLocalizedString(#"ValueAndStringFMT");
string = [string stringByReplacingOccurrencesOfString:#"[[VALUE]]"
withString:#(value).stringValue
];
string = [string stringByReplacingOccurrencesOfString:#"[[STRING]]"
withString:str
];
textLabel.text = string;
That way the worst case scenario is that a placeholder is not expanded, meaning the placeholder is visibly printed on screen but at least your app won't crash because someone messed up the localization strings file.
If you need to localize one of the format variables, then you need to do that first in an own step:
NSString * str = NSLocalizedString(#"hello");

Objective C remove end of string after certain character [duplicate]

This question already has answers here:
Remove Characters and Everything After from String
(2 answers)
Closed 8 years ago.
I can't seem to find the answer to this anywhere. I can do it in c but objective c is difficult.
I want to cut the end of a string after a certain character
so user#example.com will become user (cut at '#')
How do I do this?
This will give you the first chunk of text that comes before your special character.
NSString *separatorString = #"#";
NSString *myString = #"user#example.com";
NSString *myNewString = [myString componentsSeparatedByString:separatorString].firstObject;
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You can use a combination of substringToIndex: and rangeOfString: methods, like this:
NSString *str = #"user#example.com";
NSRange pos = [str rangeOfString:#"#"];
if (pos.location != NSNotFound) {
NSString *prefix = [str substringToIndex:pos.location];
}
Notes:
You need to check the location against NSNotFound to ensure that the position is valid.
substringToIndex: excludes the index itself, so the # character would not be included.

Converting decimal number to binary Objective-C

Hi I have made an IOS app that converts binary, hexadecimal and decimal values. It all works fine except for my decimal to binary conversion. Here is what I have. It returns 0s and 1s but far too many. Can anyone tell me why this is or help me with a better method?
NSString *newDec = [display text]; //takes user input from display
NSString *string = #"";
NSUInteger x = newDec;
int i = 0;
while (x > 0) {
string = [[NSString stringWithFormat:#"%u", x&1] stringByAppendingString:string];
x = x>> 1;
++i;
}
display.text = string; //Displays result in ios text box
Try this:
NSUInteger x = [newDec integerValue];
And next time don't ignore the Compiler's "Incompatible pointer to Integer conversion" hint...
Explanation: Afaik, assigning an object to an int, actually assigns the address of the object to that integer, not the content of the string (which is what you want).

Comparing a string in a NSMutableArray to a NSString

I'm very new to objective-c and this question may seem very simple so I am sorry if it is. I think I know how to get a user to input a string in C and comparing that to a string in an array by using strcmp. For instance (not sure if code is right as I'm not very good at c either)
char *arr[2];
arr[0] = "hello";
arr[1] = "goodbye";
char myString[10];
printf("enter greeting\n");
scanf("%s",myString);
if(strcmp(myString,arr[0]) == 0 )
{
printf("hello to you to");
}
if(strcmp(myString,arr[1]) == 0 )
{
printf("goodbye then");
}
But I'm trying to do the same thing with NSMutableArrays and NSStrings. So far it goes:
NSMutableArray *myStringArray = [[NSMutableArray alloc] init];
[myStringArray addObject:#"hello"];
[myStringArray addObject:#"goodbye"];
char greetingStr[40];
printf("enter greeting\n");
scanf("%s", greetingStr);
NSString *greeting = [NSString stringWithUTF8String:greetingStr];
//Some method to compare the strings
I was wondering what the code is the compare NSString with objects in NSMutableArrays. Sorry if it was badly explained but I am very new to programming and please keep any answers quite simple as I'm still very new to this. Thank you in advance.
"Some method to compare the strings" is:
isEqualToString:, if you're only interested in equality of strings;
compare:, if you also want to get information about their lexicographical ordering.

Detect type from string objective-c

Whats the best way of detecting a data type from a string in Objective-c?
I'm importing CSV files but each value is just a string.
E.g. How do I tell that "2.0" is a number, "London" should be treated as a category and that "Monday 2nd June" or "2/6/2012" is a date.
I need to test the datatype some how and be confident about which type I use before passing the data downstream.
Regex is the only thing I can think about, but if you are on mac or iphone, than you might try e.g. RegexKitLite
----------UPDATE----------
Instead of my previous suggestion, try this:
NSString *csvString = #"333";
NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,";
NSScanner *typeScanner = [NSScanner scannerWithString: csvString];
[typeScanner setCharactersToBeSkipped: [NSCharacterSet characterSetWithCharactersInString:charSet]];
NSString *checkString = [[NSString alloc] init];
[typeScanner scanString:csvString intoString:&checkString];
if([csvString length] == [checkString length]){
//the string "csvString" is an integer
}
To check for other types (float, string, etc.), change this line (which checks for int type) NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,"; to NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; (which checks for float type) or NSString *charSet = #"1234567890"; (which checks for a string composed only of letters).
-------Initial Post-------
You could do this:
NSString *stringToTest = #"123";
NSCharacterSet *intValueSet = [NSCharacterSet decimalDigitCharacterSet];
NSArray *test = [stringToTest componentsSeparatedByCharactersInSet:intValueSet];
if ([test count]==[stringToTest length]+1){
NSLog(#"It's an int!");
}
else {
NSLog(#"It's not an int");
}
This works for numbers that don't have a decimal point or commas as thousands separators, like "8493" and "883292837". I've tested it and it works.
Hope this provides a start for you! I'll try to figure out how to test for numbers with decimal points and strings.
Like Andrew said, regular expressions are probably good for this, but they're a bit complicated.