Objective c 串和编码的范围
我正在尝试解析使用NSTask执行的shell命令的输出。寻找一个特定的子字符串就足够了,只有子字符串永远找不到 到目前为止,我的代码是:Objective c 串和编码的范围,objective-c,nsstring,Objective C,Nsstring,我正在尝试解析使用NSTask执行的shell命令的输出。寻找一个特定的子字符串就足够了,只有子字符串永远找不到 到目前为止,我的代码是: NSPipe *pipe; pipe = [NSPipe pipe]; [task setStandardOutput: pipe]; NSFileHandle *file; file = [pipe fileHandleForReading]; [task launch]; NSData *data; data = [file readDataToE
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSLog(string);
if([string rangeOfString:@"Connection refused"].location != NSNotFound) {
NSLog(@"found");
} else {
NSLog(@"not found");
}
它始终打印“未找到”,即使搜索的子字符串包含在变量字符串中。提前谢谢。我很惊讶,但是当我把条件写反了。成功了。 请检查以下示例:
NSString *string = @"hello bla Connection refused Connection refused bla";
if ([string rangeOfString:@"Connection refused"].location == NSNotFound) {
NSLog(@"string does not contain Connection refused");
} else {
NSLog(@"string contains Connection refused!");
}
希望我是清楚的。我错了。该命令的输出实际上是空的(因此找不到明显的字符串)。我期望NSLog调用的结果实际上是命令直接输出到控制台(stderr?)。很抱歉:(.不幸的是,这并没有那么容易。当我像您一样初始化我正在搜索的字符串时,rangeOfString按预期工作(即使在非反转条件下)。问题似乎在于将已执行命令的输出转换为NSString(可能是编码还是其他?)。