Reputation: 39
I have some problems and need some help with Objective-C.
I'm trying to find a String, let's say it is called <font>
in a XML File and within the Tag I want to replace a word in a sentence.
Something like this
<body>
...
<font>Let's do a quick test</font>
...
</body>
For example:
Between <font>
and </font>
I want to replace the word quick
to good
.
And those changes has to overwrite the XML-File.
If someone can help me please let me know.
Thank you
Upvotes: 0
Views: 432
Reputation: 1780
Firstly get the string between two string using this method
NSString *str1 = [self getSubString:fullString fromRangeOfString:@"<font>" endWith:@"</font>"];
-
-(NSString *)getSubString:(NSString *)string fromRangeOfString:(NSString *)rangeStr endWith:(NSString *)endStr{
NSString *param = @"";
NSRange start = [string rangeOfString:rangeStr];
if (start.location != NSNotFound)
{
param = [string substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:endStr];
if (end.location != NSNotFound)
{
param = [param substringToIndex:end.location];
}
}
return param;
}
Now str1 contains @"Let's do a quick test" then replace the word quick to good
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:@"quick" withString:@"good"];
There are some more methods provided by Apple which help you to replace with more options
/* Replace all occurrences of the target string in the specified range with replacement. Specified compare options are used for matching target. If NSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch. */
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange NS_AVAILABLE(10_5, 2_0);
/* Replace all occurrences of the target string with replacement. Invokes the above method with 0 options and range of the whole string. */
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0);
/* Replace characters in range with the specified string, returning new string. */
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0);
................................<><><><><><><>...........................
XMLWriter *xmlWriter = [[XMLWriter alloc] init];
// start writing XML elements
[xmlWriter writeStartElement:@"font"];
[xmlWriter writeCharacters:str2];
[xmlWriter writeEndElement];
Thanks, Hope this helps you.
Upvotes: 1