I have an array and I want to check if one string is in the array, without looping. Just using "if's" I know if some string exists or not in the array.
Is there any possibility?
Use -[NSArray containsObject:].
(You don't have to write the loop yourself, but of course NSArray almost certainly has to use a loop internally.)
if ([array containsObject:string])
NSLog(#"Yes, the array contains my string.")
What about
if ([yourArray containsObject:#"string"]) {
}
??
NSarray *theArray; // assume exists
if ( [theArray containsObject:someString] )
{
...
}
Related
I have an array that contains some objects;
example:
NSArray*arr=[NSMutableArray arrayWithObjects:#1,#5,#7,#6 nil];
How I could find, for example if the array contains the number 1 and 7 without creating a loop.
Is there such a function?
For example returns a Boolean value or something?
Sure thing!
You can use this method
(BOOL)containsObject:(ObjectType)anObject;
or somethings else:
(NSUInteger)indexOfObject:(ObjectType)anObject;
(NSUInteger)indexOfObject:(ObjectType)anObject inRange:(NSRange)range;
Have fun.
Use indexOfObject to find if an element is present in your array or not :
NSNumber *num=[NSNumber numberWithInteger:7];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
NSLog(#"not found");
}
Hope this helps.
I have an NSArray of NSStrings and would like to know how to compare each item in the array with every other item in the array to see if there is any strings different from the rest.
I have seen a c++ example
for (int i = 0; i < list.size(); i++) {
for (int j = i+1; j < list.size(); j++) {
// compare list.get(i) and list.get(j)
}
}
but was woundering if there is a better easier way in objective C? also the other thing I need to do is make sure the item doesn't compare itself while it loops through.
Any help or examples would be greatly appreciated.
UPDATE ** BOLD is the updated part of the question **
If I read your question correctly, you want the strings that only appear once in the list, correct?
NSCountedSet *counted = [NSCountedSet setWithArray:list];
for (NSString *string in counted) {
NSUInteger count = [counted countForObject:string];
if (count == 1) {
// process "string", it appears in the list just once
}
}
If you just want to know if there is more than one different value in the list then do this:
NSSet *set = [NSSet setWithArray:list];
if (set.count == 1) {
// There is only one distinct value in the list
} else {
// There is more than one distinct value in the list
}
I'd use an NSMutableDictionary. This is very similar to "merging two lists into unique values", the apple docs actually explain the complicated way somewhere. I forgot where I found it, but the easy way is here: Merge two arrays while preserving the original array order
So what you'd do is loop through everything, see if there's a key (set to the string), if not, add one via the setObject: forKey: method, then enumerate through the dictionary or just grab the allKeys value after.
Use two sets. If the string goes into the first set without conflict, add it to the second set. If the string encounters a conflict in the first set, remove it from the second set. When you've processed all the strings the second set contains the unique ones.
In Xcode, I store some NSString in NSMutableArray.
Hello
Here
MyBook
Bible
Array
Name2
There
IamCriminal
User can enter string.
Name2
I need to delete that particular string from NSMutableArray without knowing index of the string. I have some idea that, Use iteration. Any other Best way. Plz Give with sample codings.
you can use containsObject method in an NSMutableArray
if ([yourArray containsObject:#"object"]) {
[yourArray removeObject:#"object"];
}
Swift:
if yourArray.contains("object") {
yourArray = yourArray.filter{ $0 != "object" }
}
[array removeObject:#"Name2"];
The documentation for NSMutableArray’s removeObject: method states:
matches are determined on the basis of an object’s response to the
isEqual: message
In other words, this method iterates over your array comparing the objects to #"Name2". If an object is equal to #"Name2", it is removed from the array.
[array removeObject:#"name2"];
You can try this
for(NSString *string in array)
{
if([[string lowercasestring] isEqualToSring:[yourString lowercasestring]])
{
[array removeObject:string];
break;
}
}
YOu can simply use
[yourArray removeObject:stringObjectToDelete];
This method uses indexOfObject: to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined on the basis of an object’s response to the isEqual: message. If the array does not contain anObject, the method has no effect.
Try this,
BOOL flag = [arrayName containsObject:Str];
if (flag == YES)
{
[arrayName removeObject:Str];
}
I've always had my doubts about Arrays.
If an Array's count is 7, and I replace the SECOND elements with 'NULL', does it still have count 7?
If an Array's count is 7, and I replace the LAST elements with 'NULL', does it still have count 7? Or will it have count 6?
I need to know this behavior to make a function that removes the first element of the Array (place '0'), and the other elements of the Array swap one place to the front.
- (void) eat {
[foodArray replaceObjectAtIndex:0 withObject:NULL];
for (int i = 0; i<[foodArray count]-1; ++i){
[foodArray replaceObjectAtIndex:i withObject:[foodArray objectAtIndex:i+1]];
}
[foodArray replaceObjectAtIndex:[foodArray count]-1 withObject:NULL];
}
Would that work?
(Thanks!)
Edit: I've just noticed the first line isn't necessary, as I'm already replacing the first element later. Am I wrong?
If you want to remove an object from an array, just use [foodArray removeObjectAtIndex:]. The way you're doing it you're just leaving a null value in the array.
Just remove the item:
- (void) eat {
[foodArray removeObjectAtIndex:0];
}
Inorder to add/remove array elements the array must be mutable: NSMutableArray so foodArray must be a NSMutableArray.
Trying to keep NULL in an array is bad idea in general.
If you need to use some kind of placeholder - it's better to use an instance of NSNull class.
Later you can check type of the object using class name check:
if( [objectFromArray isKindOfClass:[NSNull class]] == YES )
{ // This is NSNull instance, not real object }
Is there a quick method that gets the largest word from an array of words?
NSMutableArray wordlist
Something like the following should do the trick:
NSString *longest = nil;
for(NSString *str in wordlist) {
if (longest == nil || [str length] > [longest length]) {
longest = str;
}
}
I'm not aware of any simpler method.
You could use something like this example to sort an Array (but instead of the 'quality' sort in the example use a length sort on your strings) and then the longest string will be either at the top or at the end (depending on your sorting).
I don't know any objective C myself, but my solution would be to keep an integer 'longest' and a string 'longestWord' and initialise it to 0 and "". Then loop over the list and check if the current word is longer then the 'longest' value. If it is, store the new length and the current word. At the end of the loop, you have the longest word stored in the 'longestWord' variable.
Hope this helps