以下代码应该可以帮助您入门。它从标准输入读取并收集变量中的输入行inputString
,直到找到分号。
NSFileHandle *inputFile = [NSFileHandle fileHandleWithStandardInput];
NSMutableString *inputString = [NSMutableString string];
do {
// Read from stdin, check for EOF:
NSData *data = [inputFile availableData];
if ([data length] == 0) {
NSLog(@"EOF");
break;
}
// Convert to NSString, replace newlines by spaces, append to current input:
NSMutableString *tmp = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[tmp replaceOccurrencesOfString:@"\n" withString:@" " options:0 range:NSMakeRange(0, [tmp length])];
[inputString appendString:tmp];
// Check for semi-colon:
} while ([inputString rangeOfString:@";"].location == NSNotFound);
NSLog(@"input=%@", inputString);
(请注意,此示例代码仅检查输入中某处的分号。它不检查分号是否例如嵌入在字符串中。)