如何使用Objective C查找和替换文件中的文本?

Con*_*onk 2 xcode objective-c xcode4

我是Xcode的新手,想知道是否有人可以帮助我.

我需要创建一个能够打开文件并替换其内容的应用程序.

例如(在伪代码中)

替换("String1","String2","〜/ Desktop/Sample.txt")

如果我不够清楚,请告诉我.

提前致谢.

Mou*_*hna 6

use stringByReplacingOccurrencesOfString:withString:方法,它将查找所有出现的一个NSString并替换它们,返回一个新的自动释放的NSString.

NSString *source = @"The rain in Spain";

NSString *copy = [source stringByReplacingOccurrencesOfString:@"ain"
                                                   withString:@"oof"];

NSLog(@"copy = %@", copy);
// prints "copy = The roof in Spoof"
Run Code Online (Sandbox Code Playgroud)

编辑

在你的字符串中设置文件内容(小心,如​​果你的文件有点大,这是不方便的),替换出现然后复制到一个新文件:

// Instantiate an NSString which describes the filesystem location of
// the file we will be reading.
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Sample.txt"];

NSError *anError;

NSString *aString = [NSString stringWithContentsOfFile:filePath
                                              encoding:NSUTF8StringEncoding
                                                 error:&anError];

// If the file read was unsuccessful, display the error description.
// Otherwise, copy the string to your file.
if (!aString) {
    NSLog(@"%@", [anError localizedDescription]);
} else {
      //replace string1 occurences by string2

      NSString *replacedString = [aString stringByReplacingOccurrencesOfString:@"String1"
                                                   withString:@"String2"];


     //copy replacedString to sample.txt
      NSString * stringFilepath = @"ReplacedSample.txt";
    [replacedString writeToFile:stringFilepath atomically:YES encoding:NSWindowsCP1250StringEncoding error:error];
}
Run Code Online (Sandbox Code Playgroud)