-1

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.

suse
  • 10,503
  • 23
  • 79
  • 113
  • I need to take the string WIPRO in Str1 and Class_Name1 in Str2, i.e Str1=WIPRO & Str2=Class_Name1,and load this Str2 Class_Name1 and again for next iteration , how the control goes to next line?? There is not getLine() in Objective-C. – suse Feb 05 '10 at 05:12

3 Answers3

1

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
  • 2,084
  • 13
  • 15
1

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;
}
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • its giving me ERROR: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (1)' – suse Feb 05 '10 at 03:57
  • 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. – Alex Wayne Feb 05 '10 at 17:47
  • The gotcha with this approach is that O(fileSize) memory & speedwise. For large files, consider getline(3) or see http://stackoverflow.com/questions/3707427/how-to-read-data-from-nsfilehandle-line-by-line#3711079 – Frederik Feb 17 '14 at 14:50
0

Regular expressions might makes this a whole lot easier. Checkout this answer: Regular expressions in an Objective-C Cocoa application

Community
  • 1
  • 1
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337