我是Xcode的新手,想知道是否有人可以帮助我。如何使用Objective C查找和替换文件中的文本?
我需要创建一个能够打开文件并替换其内容的应用程序。
例如(在伪代码)
替换( “字符串1”, “字符串2”, “〜/桌面/ Sample.txt的”)
请让我知道,如果我不够清晰。
在此先感谢。
我是Xcode的新手,想知道是否有人可以帮助我。如何使用Objective C查找和替换文件中的文本?
我需要创建一个能够打开文件并替换其内容的应用程序。
例如(在伪代码)
替换( “字符串1”, “字符串2”, “〜/桌面/ Sample.txt的”)
请让我知道,如果我不够清晰。
在此先感谢。
你可能想this
以及关于你如何从文件中读取文本问题到的NSString:
NSError * error;
NSString * stringFromFile;
NSString * stringFilepath = @"loadfile.txt";
stringFromFile = [[NSString alloc] initWithContentsOfFile:stringFilepath
encoding:NSWindowsCP1250StringEncoding
error:&error];
以及用于写入到一个文件: (使用加载相同的NSString:stringFromFile)
NSError * error;
NSString * stringFilepath = @"savefile.txt";
[stringFromFile writeToFile:stringFilepath atomically:YES encoding:NSWindowsCP1250StringEncoding error:error];
注意,在这个例子中我使用用于Windows的编码(这意味着它在每行的末尾使用charcters \ n \ r)。检查其他类型的编码的文档。
(见NSString
文档)
使用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"
编辑
设置文件的内容在你的字符串(注意,如果你的文件是有点大,这是不conveniant),取代OCCURENCES然后复制到一个新的文件:
// 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];
}
如何将* source设置为文本文件的完整内容?那我该如何将复制的值写入文件呢? – Conk
+1为凝聚力的示例代码 – phlebotinum
我其实认为你的答案更好... – phlebotinum
您可能希望[这](http://stackoverflow.com/questions/668228/string-replacement-in-objective-c) – phlebotinum