解析保存到文本文件的字符串

发布于 2024-11-10 07:12:00 字数 264 浏览 3 评论 0原文

我将 Cocoa 应用程序中的数据保存到文本文件中。文本文件包含的信息如下所示:

foo1 -> foo2
blah -> lwjef
hi -> bye
hello -> goodbye

现在每行的第一部分由用户给出,但我需要获取每行在 -> 之后的部分。例如,如果用户输入foo1,我想在解析文本文件后输出foo2。有谁知道该怎么做?

I save pieces of data from my Cocoa application into a text file. The text file contains information as shown:

foo1 -> foo2
blah -> lwjef
hi -> bye
hello -> goodbye

Now the first part of each row is given by the user, but I need to get the part of each row after the ->. For example, if the user enters foo1, I want to output foo2 after parsing the text file. Does anyone know how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里兽 2024-11-17 07:12:00

解析一次:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *lines = [string componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
    NSArray *values = [line componentsSeparatedByString:@" -> "];
    if ([values count] != 2) {
        continue;
    }
    [dictionary setObject:[values objectAtIndex:1] forKey:[values objectAtIndex:0]];
}

然后查询密钥:

NSString *input = @"foo1";
NSString *answer = [dictionary objectForKey:input]; //@"foo2"

但是,如果数据最初来自您自己的应用程序,您可能应该这样做,而不是自定义(且不安全)的字符串格式:

//For saving:
[dictionary writeToFile:filePath atomically:YES];
//For loading:
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];

Parse once:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *lines = [string componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
    NSArray *values = [line componentsSeparatedByString:@" -> "];
    if ([values count] != 2) {
        continue;
    }
    [dictionary setObject:[values objectAtIndex:1] forKey:[values objectAtIndex:0]];
}

Then query for keys:

NSString *input = @"foo1";
NSString *answer = [dictionary objectForKey:input]; //@"foo2"

However, if the data originally came from your own application in the first place you should probably do this, instead of a custom (and insecure) string format:

//For saving:
[dictionary writeToFile:filePath atomically:YES];
//For loading:
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文