2015-05-01 20 views
0

我正在編寫一個程序,該程序在每次運行時都會將關於某人的信息記錄到文本文件(累積)中。提示用戶輸入名字,姓氏,喜歡的顏色,關係狀態(單身/約會)等信息。還有一個分配的票號是自動的和順序的(ticketNumber ++每次打印後)。替換TextFile.txt中指定的字符串的出現

輸出文件(可以稱之爲outputLog.txt)看起來是這個協議:

Time In: 12:57 PM (Apr 30, 2015) 
Name: John Doe 
Ticket: 31393 
Color: Green 
Relationship Status: single 

Time In: 1:58 PM (Apr 30, 2015) 
Name: Jane Doe 
Ticket: 31394 
Color: Yellow 
Relationship Status: married 

我希望能夠做到,當與票號提示,就是找到那個人並在someFile.txt中更改關係狀態。

到目前爲止我所能做的是使用一個相當簡單的「if語句」來查看文件。如果找到該號碼,則用新的關係狀態替換,否則返回錯誤消息。這裏是一段代碼:

// First a ticket number is stored in --> unsigned int ticketCalled 

requestTicket = [NSString stringWithFormat:@"%d", ticketCalled]; // (int --> string) 

NSError *error; 
NSString *intFilePath = @"/filepath.txt"; 

NSString *someTicket = [[NSString alloc] initWithContentsOfFile:intFilePath 
                 encoding:NSUTF8StringEncoding 
                  error:&error]; 

if (!requestTicket) { 
    NSLog(@"%@", [error localizedDescription]); 
} else { 
    NSString *replacedString = [someTicket stringByReplacingOccurrencesOfString:requestTicket 
                    withString:@"divorced"]; 
    [replacedString writeToFile:intFilePath 
        atomically:YES 
         encoding:NSUTF8StringEncoding 
          error:&error]; 
    NSLog(@"\r Relationship status successfully changed!"); 
} 

顯然這不正是我想要的。上述代碼所做的是替換用新關係狀態指定的票號。我想要做的是使用關聯的故障單號找到文本文件中的對象(輸出文本塊),然後找到關係狀態並更改其附加文本。感謝您的期待!

+0

你說的是尋找在票號文本文件。我對麼? –

+0

是的,先生,文本文件中的數字。然後往下走兩條線並更換字符串。 (我會編輯問題以說明問題。我的不好) – James

回答

0

你可以嘗試找到這個准考證號:

NSRange isRange = [someTicket rangeOfString:@"31393 "  options:NSCaseInsensitiveSearch]; 
if(isRange.location == 0) { 
    //found it... 
     [self changeStatus]; 
} else { 
NSRange isSpacedRange = [someString rangeOfString:@" 31393 " options:NSCaseInsensitiveSearch]; 
if(isSpacedRange.location != NSNotFound) { 
    //found it... 
    [self changeStatus]; 
    } 
} 

這裏是改變現狀的方法:

-(void)changeStatus{ 

NSString *newString = [someTicket stringByReplacingOccurrencesOfString:@"single" withString:@"married"]; 

} 
+0

找到票號並不是問題。問題是票號正在被新的字符串替換。找到票號後,我無法弄清楚如何執行以下操作:找到位於票號下方的行 - >搜索字符串 - >替換字符串。 – James

相關問題