-3

suppose i have a string as follows

NSString *samp =@"abc def ghi abc ijk def abc abc ghi";

I need to print output as

abc = 4;

def = 2;

ghi = 2;

ijk = 1;

this is the following code but i am unable to compare elements inside array

    var s1 = "abc def ghi jkl abc def mno";
    var a = s1.componentsSeparatedByString(" ");

Kindly help me in solving this.

yashwanth
  • 1
  • 4

2 Answers2

0

This will give you an array:

NSString *myString = @"abc def ghi abc ijk def abc abc ghit";
NSArray *myWords = [myString componentsSeparatedByString:@" "];

This will turn it into a set:

NSCountedSet *mySet = [[NSCountedSet alloc] initWithArray:myWords];

This will loop through the set:

for (id item in mySet) 
{
    NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
Mika
  • 5,807
  • 6
  • 38
  • 83
-1

This is not a site where other people write code for you. It's a site for help solving problems for yourself.

Take a look at the NSString class. There are a number of methods for searching for substrings, breaking up strings using a delimiter, etc. Take a look at rangeOfString and it's variations. Also look at componentsSeparatedByString, which will break up a word into substrings.

You could break the string into substrings using componentsSeparatedByString, then use the array of strings to initialize an NSCountedSet. That would give you your desired result in about 2 lines of code.

There is also NSScanner, which you can use to search for substrings in a string.

Off the top of my head I can think of 3 or 4 ways to solve your problem using those tools. Take a stab at it and see what you can come up with. If you have problems making your ideas work, THEN come back for help.

Duncan C
  • 128,072
  • 22
  • 173
  • 272