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

标签 objective-c xcode xcode4

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

我需要制作一个能够打开文件并替换其内容的应用程序。

例如(在伪代码中)

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

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

提前致谢。

最佳答案

使用 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"

编辑

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

// 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];
}

关于objective-c - 如何使用 Objective C 查找和替换文件中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7121532/

相关文章:

ios - 自定义 UIActivity 的主题

ios - 如何在 IOS 7 的 xcode 中加载新图标?

ios - 如何使 UIToolbar 出现在 Storyboard 中以进行可视化编辑

ios - Xcode 可以在 XIB 中查找/替换吗?

iphone - 不想将内容集中在 UITableViewCell

iphone - 如何停止 NSRunLoop

objective-c - 尝试使用return退出方法,但实际上未返回任何内容

iphone - 如何在我的整个 xml 字符串中将双引号转义为\"?

Xcode 方案 : Can't Select Build Configuration

iphone - 在 Objective-C 中释放对象的正确方法是什么