【发布时间】:2014-05-20 11:51:47
【问题描述】:
我正在尝试编写一些简单的代码,用于在两个字典中搜索一个字符串,如果该字符串出现在两个字典中,则打印到控制台。我希望用户能够通过控制台输入字符串,然后将字符串作为变量传递到消息中。我想知道如何从控制台处理getting 字符串并将其用作以下方法调用中的参数。
[x rangeOfString:"the string goes here" options:NSCaseInsensitiveSearch];
我不确定如何从用户那里获取字符串。我是使用 scanf() 还是 fgets() 转换为 char,然后将其转换为 NSSstring,还是简单地扫描为 NSString 本身。然后我想知道如何将该字符串作为参数传递。请帮忙:
这是我到目前为止的代码。我知道这并不简洁,但我只想完成工作:
#import <Foundation/Foundation.h>
#include <stdio.h>
#include "stdlib.h"
int main(int argc, const char* argv[]){
@autoreleasepool {
char *name[100];
printf("Please enter the name you wish to search for");
scanf("%s", *name);
NSString *name2 = [NSString stringWithFormat:@"%s" , *name];
NSString *nameString = [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
NSString *dictionary = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];
NSArray *nameString2 = [nameString componentsSeparatedByString:@"\n"];
NSArray *dictionary2 = [dictionary componentsSeparatedByString:@"\n"];
int nsYES = 0;
int dictYES = 0;
for (NSString *n in nameString2) {
NSRange r = [n rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
nsYES = 1;
}
}
for (NSString *x in dictionary2) {
NSRange l = [x rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (l.location != NSNotFound){
dictYES = 1;
}
}
if (dictYES && nsYES){
NSLog(@"glen appears in both dictionaries");
}
}
}
谢谢。
【问题讨论】:
标签: objective-c input stdin scanf