Comparing a string in a NSMutableArray to a NSString - objective-c

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.

Related

ReConvert NSString to NSArray

I have converted an NSArray to NSString using below code
Suppose i have an array with some data in it.
NSString *sample=[array description];
NSLog(#"%#",sample);
which prints:
(
{
URL = "1a516af1a1c6020260a876231955e576202bbe03.jpg##37911944cc1ea8fd132ee9421a7b3af326afcc19.jpg";
userId = 0;
wallpaperId = 31;
},
{
URL = "a9356863fa43bc3439487198283321622f88e31f.jpg##f09c743ebdc26bb9f98655310a0529b65a472428.jpg";
userId = 0;
wallpaperId = 30;
}
)
It looks like array but it is actually a string.
Now I am wondering, how can I reconvert back to NSArray?
Help appreciated.
And please this not a duplicate question, I couldn't found the same anywhere on SO.
You cannot rely on the results of description as it is not a convert to string operator, but merely a debugging aid. There is nothing to stop it changing between O/S releases and there is no equivalent fromDescription method.
The conventional way of serializing an Objective-C collection to and from a string is to use JSON, so look at the NSJSONSerialization class.
the
NSString componentsseparatedbystring
method will return an array of components separated by a string

Finding array objects from user input

I'm trying to make it so the user input for my code corresponds with the objects in my array, but I have no idea how to do this.
Basically, the assignment says to right a program that will grade final exams, each question has one of four possible answers ( a,b,c,d) and the first answer in the array should correspond to the first question in the exam. The program should them prompt the user for their answers to the exam, and should be compared with the first correct answer in the array and if it matches, it'll give them points.
Problem is, I can't for the life of me figure out how to compare user input to my array to see if it's the right thing they put in.
Here's what I have so far!
I know I'm awful at it, but I'm trying my best. Any help will be extremely appreciated.
#import <Foundation/Foundation.h>
int main (int argc, char * argv[])
{
#autoreleasepool {
NSArray *correctAnswers= [NSArray arrayWithObjects: #"a", #"b ", #"c", #"d",nil];
int sum = 0;
int anwser;
{
NSLog(#"Please input test anwsers starting with 1:");
scanf("%i",&anwser);
}
if ([correctAnswers containsObject:#(anwser)]) {
sum = +10;
}else {
NSLog(#"Well that's not quite right...");
}
NSLog(#"The final score is:%d",sum);
}
return 0;
}
#"a" etc are NSString instances.
You would need to use NSString instance methods to compare them to the user input. You can also do fast enumeration with collections like NSArray
for (NSString* ans in correctAnswers)
{
if ([ans isEqualtoString:[NSString stringWithInt:anwser]]) sum+=10;
}
You could also use NSArray's filteredArrayUsingPredicate: to search the array.
But you can't use containsObject to compare strings... it just checks for a specific NSObject instance.
You also appear to be comparing an int to a char... but that's outside the scope of your question.

Converting a string variable from Binary to Decimal in Objective C

Im trying to create a Binary to Decimal calculator and I am having trouble doing any sort of conversion that will actually work. First off Id like to introduce myself as a complete novice to objective c and to programming in general. As a result many concepts will appear difficult to me, so I am mostly looking for the easiest way to understand and not the most efficient way of doing this.
I have at the moment a calculator that will accept input and display this in a label. This part is working fine and I have no issues with it. The variable that the input is stored on is _display = [[NSMutableString stringWithCapacity:20] retain];
this is working perfectly and I am able to modify the data accordingly. What I would like to do is to be able to display an NSString of the conversion in another label. At the moment I have tried a few solutions and have not had any decent results, this is the latest attempt
- (NSMutableString *)displayValue2:(long long)element
{
_str= [[NSMutableString alloc] initWithString:#""];
if(element > 0){
for(NSInteger numberCopy = element; numberCopy > 0; numberCopy >>= 1)
{
[_str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
}
}
else if(element == 0)
{
[_str insertString:#"0" atIndex:0];
}
else
{
element = element * (-1);
_str = [self displayValue2:element];
[_str insertString:#"0" atIndex:0];
NSLog(#"Prima for: %#",_str);
for(int i=0; i<[_str length];i++)
_str = _display;
NSLog(#"Dopo for: %#",_str);
}
return _str;
}
Within my View Controller I have a convert button setup, when this is pressed I want to set the second display field to the decimal equivalent. This is working as if I set displayValue2 to return a string of my choosing it works. All I need is help getting this conversion to work. At the moment this bit of code has led to "incomplete implementation" being displayed at the to of my class. Please help, and cheers to those who take time out to help.
So basically all you are really looking for is a way to convert binary numbers into decimal numbers, correct? Another way to think of this problem is changing a number's base from base 2 to base 10. I have used functions like this before in my projects:
+ (NSNumber *)convertBinaryStringToDecimalNumber:(NSString *)binaryString {
NSUInteger totalValue = 0;
for (int i = 0; i < binaryString.length; i++) {
totalValue += (int)([binaryString characterAtIndex:(binaryString.length - 1 - i)] - 48) * pow(2, i);
}
return #(totalValue);
}
Obviously this is accessing the binary as a string representation. This works well since you can easily access each value over a number which is more difficult. You could also easily change the return type from an NSNumber to some string literal. This also works for your element == 0 scenario.
// original number wrapped as a string
NSString *stringValue = [NSString stringWithFormat:#"%d", 11001];
// convert the value and get an NSNumber back
NSNumber *result = [self.class convertBinaryStringToDecinalNumber:stringValue];
// prints 25
NSLog(#"%#", result);
If I misunderstood something please clarify, if you do not understand the code let me know. Also, this may not be the most efficient but it is simple and clean.
I also strongly agree with Hot Licks comment. If you are truly interested in learning well and want to be an developed programmer there are a few basics you should be learning first (I learned with Java and am glad that I did).

Compare char array with string in iOS program [duplicate]

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
}

Matching Strings in Objective C

I have a for loop which loops through an array and want to match a search field's text to an object in the array.
I have the following code
for (int i = 0; i < [data2 count]; i++) {
if ([data2 objectAtIndex:i] == searchField.text) {
NSLog(#"MATCH");
break;
}
}
I know in Java it can be done by e.g. if(searchField.text.equalsIgnoreCase(the object to match against))
How is this done in objective C, to match the string without case?
Also, what if I wanted to match part of the string, would that be done in Obj C char by char or is there a built in function for matching parts of Strings?
Thanks
Assuming your strings are NSStrings, you can find your answers at the NSString Class Reference
NSString supports caseInsensitiveCompare: and rangeOfString: or rangeOfString:options: if you want a case insensitive search.
The code would look like this:
if (NSOrderedSame == [searchField.text caseInsensitiveCompare:[data2 objectAtIndex:i]) {
// Do work here.
}
[[data2 objectAtIndex:i] isEqualToString: searchField.text]
You use isEqual: (to compare objects in general) or isEqualToString: (for NSStrings specifically). And you can get substrings with the substringWithRange: method.