codebot
codebot

Reputation: 2646

How to find a string and replace a substring of it in iOS?

I have a string like following,

# Blender v2.72 (sub 0) OBJ File: 'untitled.blend'
# www.blender.org
mtllib test03.mtl
o Cube.001
v 3.851965 0.040851 6.046364
v 3.851965 0.087396 6.092909
v -3.851965 0.087396 6.092909

I need to read the 3rd line(mtllib test03.mtl) and replace the test03.mtl with test04.mtl. Then the final line should be like following,

# Blender v2.72 (sub 0) OBJ File: 'untitled.blend'
# www.blender.org
mtllib test04.mtl
o Cube.001
v 3.851965 0.040851 6.046364
v 3.851965 0.087396 6.092909
v -3.851965 0.087396 6.092909

I tried to do it with the following code,

NSString* str= @"mtllib test03.mtl";

// Search from back to get the last space character
NSRange range= [str rangeOfString: @"mtllib " options:NSBackwardsSearch];

// Take the first substring: from 0 to the space character
NSString* finalStr = [str substringToIndex: range.location];
NSLog(@"%@", finalStr);

but failed to loads the line(mtllib test03.mtl) from above lines. How can I fix this.

Thanks in Advance!

Upvotes: 1

Views: 113

Answers (1)

glyuck
glyuck

Reputation: 3397

You can use regular expression:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^mtllib (.*)$" options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"mtllib test04.mtl"];
if (error) {
    NSLog(@"Error: %@", error);
}
NSLog(@"%@", modifiedString);

And solution without regexp:

NSString *str = @"# Blender v2.72 (sub 0) OBJ File: 'untitled.blend'\n\
# www.blender.org\n\
mtllib test03.mtl\n\
o Cube.001\n\
v 3.851965 0.040851 6.046364\n\
v 3.851965 0.087396 6.092909\n\
v -3.851965 0.087396 6.092909";
NSString *finalStr = str;

// Find "mtllib" substring
NSRange range= [str rangeOfString: @"mtllib " options:NSBackwardsSearch];
// This is location of filename, now we need to find it's range
CGFloat fileNameLocation = range.location + range.length;
// Find first end of line after "mtllib" substring
NSRange newlineRange = [str rangeOfString:@"\n" options:0 range:NSMakeRange(fileNameLocation, str.length-fileNameLocation)];
if (newlineRange.location != NSNotFound) {
    NSRange filenameRange = NSMakeRange(fileNameLocation, newlineRange.location - fileNameLocation);
    finalStr = [str stringByReplacingCharactersInRange:filenameRange withString:@"test04.mtl"];
} else {
    // Assume, there is no more data in string, only filename
    NSRange filenameRange = NSMakeRange(fileNameLocation, str.length - fileNameLocation);
    finalStr = [str stringByReplacingCharactersInRange:filenameRange withString:@"test04.mtl"];
}
NSLog(@"%@", finalStr);

Upvotes: 2

Related Questions