Mario
Mario

Reputation: 17

Finding element in array

I have the follow code:

NSArray *myArray = [NSArray arrayWithObjects: @"e", @"è", @"é",@"i","ò",nil];

NSString *string = @"simpleè";
NSMutablestring *newString;

for(i=0>;i< [string length]; i++){
  if([stringa characterAtIndex:i] is in Array){
   [newString appendFormat:@"%c", [string characterAtIndex:i]];
 }
}

How make finding if single char of string stay in the array?
Example of result:
newString= @"ieè";

Upvotes: 0

Views: 177

Answers (5)

Luke
Luke

Reputation: 7220

There are better ways to do this, but this is what I think you're trying to do:

NSMutableString* result= [NSMutableString stringWithString:@""];

for( int i= 0; i < [string length]; ++i ) {

    NSString* c= [NSString stringWithFormat:@"%C", [string characterAtIndex:i]];

    if( [myArray containsObject:c] )
        [result appendString:c];
}

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47759

I think you want to apply rangeOfCharacterFromSet:options:range: repeatedly. You'll have to create a NSCharacterSet from the characters in your array somehow.

Added

Though it probably would be just as simple to just loop through the string with characterAtIndex and compare each char (in an inner loop) to the chars in your array (which you could extract into a unichar array or put into a single NSString to make easier to access).

Upvotes: 1

Chuck
Chuck

Reputation: 237110

You'll want to create an NSCharacterSet with the characters in the string and then ask each string in the array for its rangeOfCharacterFromSet:. If you find one where a range was actually found, then a character from the string is in the array. If not, then none of them are.

This might seem a bit roundabout, but Unicode makes looking at strings as just a series of "chars" rather unreliable, and you'll want to let your libraries do as much of the heavy lifting for you as they can.

Upvotes: 0

Aman Aggarwal
Aman Aggarwal

Reputation: 3754

You should check the length of your string and then match your string characters with the array and if found append that character in a new string.

 NSString *mstr = @"asdf";
  NSString *b = [ mstr characterAtIndex:0];  

Hope it helps.......

Upvotes: 0

Gabriel
Gabriel

Reputation: 3045

Umm... if you want to check what the values are you can use NSLog

NSLog"%f", myFloat;

So you can use this to check your array... Which is what I think you are asking for, but the grammar in your question isn't very good. Please provide more details and better grammar.

Upvotes: 0

Related Questions