views:

306

answers:

3

I am writing a string tokenizer in Objective-C for an iPhone application.

I have the result as:

1|101|Y|103|Y|105|Y|107|Y|109|Y|111|Y|113|Y|115|Y|

I want to tokenize this string and display each of the values in tabular format. How am I to do it?

I want the result in a tabular format. Like:

102 Y
103 Y
..  ...
+7  A: 

If by “tokenizing” you mean simply “splitting on the pipe-sign”, you can use the componentsSeparatedByString: method of NSString:

 NSString *original = @"1|101|Y|103|Y|105…";
 NSArray *fields = [original componentsSeparatedByString:@"|"];

“Displaying in a tabular format” doesn’t say much. If you want a classic table, see the UITableView class.

zoul
A: 

Not sure why you want this specifically in Objective-C (are you looking for a tokenizer class?), but generic strsep() resp. iso-c90 strtok() / strtok_r() do this and they exist on Mac OS X and on iPhone OS. Described here:

http://developer.apple.com/iPhone/library/documentation/System/Conceptual/ManPages%5FiPhoneOS/man3/strsep.3.html

These got code quotes as well.

FrankH.
A: 

This solution is in C if you need it.

Let's say you have 16 elements in total. You will have 8 rows and 2 columns. Declare 16 pointers like this:

    char *str[8][2]={NULL}

    int j=0,k=0;

    while (pch != NULL && i < 16)
    {
        str[i]=(char*)malloc(strlen(pch) + 1);
        strcpy(str[j][k],pch);
        pch = strtok (NULL, "*");
        i++;
        j++;
        k++;
        if (k==2)
            k=0;
    }

Then you will have an array:

    str[num of rows][num of columns]

Print these pointers in whatever way you need.

    for (l=0;l<8;l++)
      for (m=0;m<2;m++)
    printf("%s %s\n",str[l][m])

There might be some compilation errors that needs to be handled by you. This solution just gives you a brief logic of how to do it.

Vijay Sarathi
Sorry, –1 from me, as I would stay away from pointers, malloc and C-strings as long as possible.
zoul
@zoul,evrybody has his own style of answering u cannot the answer is not useful.point out the mistake in it and then give -1 ..then i agree.
Vijay Sarathi
11 lines of code instead of 1? Probably not the right approach.
nall
The question is based on Objective-C, a C answer (particularly an overly complex C answer that is not even a good way to do this in C) is simply not needed nor desirable. The mistake is ever posting this.
Kendall Helmstetter Gelner