views:

75

answers:

2

Hi, everyone,

I want to ask an NSString * question. I have a NSString * object. The content is like the following example. (like the CSV file)

Example: (my file is longer than this one so much)

First Name,Last Name,Middle Name,Phone,Chan,Tim,Man,123-456-789,Tom,,,987-654-321

(if it is empty, no space between the ',')

How can I insert the "(null)" NSString * / or NSString * object between the two ',' by using the objective C?

// After convent

First Name,Last Name,Middle Name,Phone,Chan,Tim,Man,123-456-789,Tom,(null),(null),987-654-321

Thank you very much.

+3  A: 

Have a look at the method stringByReplacingOccurrencesOfString:withString: (untested):

NSString *newString = [oldString stringByReplacingOccurrencesOfString:@",," 
                                                           withString:@",(null),"];

This might be sufficient for your needs.

Felix Kling
A: 

I'm a beginner in Objective-C and I didn't test this answer, but I think it does the job.

//given your NSString called string
NSArray *pieces = [[NSArray alloc] initWithArray: [string componentsSeparatedByString:@","]];

NSMutableString *final = [[NSMutableString alloc] init];

for(int i; i < [pieces count]; i++)
{
    if(i > 0)
        [final appendString: [NSString stringWithFormat:@","]];

    if([pieces objectAtIndex: [NSNumber numberWithInt: i]] == nil)
    {
        [final appendString: [NSString stringWithFormat:@"(null)"]];
    }
    else
    {
        [final appendString: [pieces objectAtIndex: [NSNumber numberWithInt: i]]];
    }
}

I hope I didn't screw it up too bad :)

Bogdan Constantinescu