2011-08-19 93 views
2

我是Xcode的新手,想知道是否有人可以幫助我。如何使用Objective C查找和替換文件中的文本?

我需要創建一個能夠打開文件並替換其內容的應用程序。

例如(在僞代碼)

替換( 「字符串1」, 「字符串2」, 「〜/桌面/ Sample.txt的」)

請讓我知道,如果我不夠清晰。

在此先感謝。

+0

您可能希望[這](http://stackoverflow.com/questions/668228/string-replacement-in-objective-c) – phlebotinum

回答

2

你可能想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文檔)

1

對於Xcode 4,打開要搜索的文件,然後單擊編輯>查找>查找和替換,或鍵盤快捷鍵Command + Option + f。

+0

我需要做的是創造一個改變我的電腦上文件內容的應用程序。我希望過程自動化。 – Conk

+1

糟糕 - 看起來像我需要另一杯茶,讓我更仔細地閱讀。 –

+0

你做了一個意外的搞笑! – doge

6

使用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]; 
} 
+0

如何將* source設置爲文本文件的完整內容?那我該如何將複製的值寫入文件呢? – Conk

+0

+1爲凝聚力的示例代碼 – phlebotinum

+1

我其實認爲你的答案更好... – phlebotinum

相關問題