views:

332

answers:

3

Hello, i've to read a .txt file , The file lokes like,

WIPRO=Class_Name1
TCS=Class_Name2

Now i want to Class_Name1 and Class_Name2.How to get this string in Objective-C? I'm not finding any function in NSString to get the index of a character.Like how we have getIndex() in C#.tel me how to proceed.

+1  A: 

The NSString Reference has an entire subheading named "Finding Characters and Substrings."

Finding Characters and Substrings

– rangeOfCharacterFromSet:
– rangeOfCharacterFromSet:options:
– rangeOfCharacterFromSet:options:range:
– rangeOfString:
– rangeOfString:options:
– rangeOfString:options:range:
– rangeOfString:options:range:locale:
– enumerateLinesUsingBlock:
– enumerateSubstringsInRange:options:usingBlock:

Dewayne Christensen
A: 

Regular expressions might makes this a whole lot easier. Checkout this answer: http://stackoverflow.com/questions/422138/regular-expressions-in-an-objective-c-cocoa-application

Squeegy
Regular expressions are gross overkill for such a simple file format.
bbum
You are probably right. `componentsSeparatedByString:` is probably all this really needs.
Squeegy
A: 

Ok, will try again. This format is pretty simple.

componentsSeparatedByString: is the magic method you want. Use it to break the text string into an array for each line, and then break each line to access the lines key and value on each side of the =.

- (NSDictionary*)dictFromConfigString:(NSString*)myTxtFileAsString {
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    NSArray *lines = [myTxtFileAsString componentsSeparatedByString:@"\n"];
    for (NSString *line in lines) {
        NSArray *pair = [line componentsSeparatedByString:@" = "];
        NSString *key = [pair objectAtIndex:0];
        NSString *value = [pair objectAtIndex:1];
        [result setObject:value forKey:key];
    }
    return result;
}
Squeegy
its giving me ERROR: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (1)'
suse
Well this assumes that each line is exactly the format you specified. If you are getting this, that means some lines are not. You may want to add some error checking to make sure each line is how you think it is before further processing it. This was just a stub for you to expand on. Set a breakpoint in this method somewhere and see what the string are and then inspect and handle those cases.
Squeegy