简体   繁体   English

如何从Objective-C中的文本文件解析坐标?

[英]How to parse coordinates from a text file in Objective-C?

I have a text file named coordinates.txt with some coordinates in it(surprisingly). 我有一个名为coordinates.txt的文本文件,其中有一些坐标(令人惊讶地)。 The format looks like this: 格式如下:

20.580070,47.775910, 
20.582950,47.776640, 
20.585660,47.777460, 
20.587280,47.777960, 
20.588280,47.778300, 
20.621870,47.789710,

I want to parse through the file, and add the first coordinate to an int variable named latitude and the second one to an int variable named longitude. 我想解析文件,然后将第一个坐标添加到名为latitude的int变量中,将第二个坐标添加到名为经度的int变量中。 Than print out the two variables to the console and do this for every line separately.I know I should use a loop but I am not exactly sure how so can you guys please help me out! 比将两个变量打印到控制台并分别对每一行执行此操作。我知道我应该使用循环,但是我不确定到底如何才能帮助我!

EDIT: 编辑:

Here is my code so far: 到目前为止,这是我的代码:

        NSString *latitude = @"0";
        NSString *longitude = @"0";
        NSString* filePath = @"/Users/Balazs/coordinates.txt";



        NSString *entireFileInString = [NSString stringWithContentsOfFile:filePath];
        NSArray *lines = [entireFileInString componentsSeparatedByString:@","];
        for (NSString *line in lines) {
                latitude = line;
        }
        NSLog([NSString stringWithFormat:@"%@",latitude]);

I know how to read the whole text into the latitude variable but not just the first part and not line by line. 我知道如何将整个文本读入纬度变量,而不仅仅是第一部分而不是逐行阅读。 Also the text which is read is stored as a string so I am not sure how to convert those into doubles.. 另外,读取的文本存储为字符串,因此我不确定如何将其转换为双精度。

PS: Sorry for the noob question!!:/ PS:对不起,菜鸟问题!!:/

Assuming the text file's in your bundle, you can store the text in an NSString like so: 假设文本文件在您的包中,则可以将文本存储在NSString如下所示:

NSString* path = [[NSBundle mainBundle] pathForResource:@"coordinates" 
                                                 ofType:@"txt"];

NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

Then separate the text into lines using componentsSeparatedByString: , go through each line with a loop, then separate each line again using componentsSeparatedByString: into its longitude and latitude values before printing. 然后使用componentsSeparatedByString:将文本分成几行,循环遍历每一行,然后在打印之前使用componentsSeparatedByString:再次将每一行分成其经度和纬度值。 For example: 例如:

NSArray *lines = [content componentsSeparatedByString:@"\n"];
for (NSString *line in lines) {
    NSArray *values = [line componentsSeparatedByString:@","];
    double latitude = [[values objectAtIndex:0] doubleValue];
    double longitude = [[values objectAtIndex:1] doubleValue];
    NSLog(@"%f, %f", latitude, longitude);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM