【问题标题】:How to read seperate fields in a csv file and compare with user input?如何读取 csv 文件中的单独字段并与用户输入进行比较?
【发布时间】:2012-09-17 08:38:07
【问题描述】:

我正在构建一个应用程序,用户可以在其中上传一个 csv 文件,其中包含 3 个单独的列中的名字、姓氏和电子邮件。用户界面将有 3 个文本字段和一个按钮。当用户输入名字或姓氏或电子邮件,并单击搜索按钮时,必须搜索整个文档并显示警报,说明在文件中找到了记录。这是我正在使用的函数,但它只读取第一行和第一列。请帮忙

- (void) SearchStudent

{

    NSArray *DocumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);



    NSString *DocumentDirectory = [DocumentPath objectAtIndex:0];



    NSString *FullPath = [DocumentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"example.csv"]];



    NSString * pstrCSVFile= [NSString stringWithContentsOfFile:FullPath encoding:NSASCIIStringEncoding error:NULL];



    NSArray * paRowsOfCSVFile= [pstrCSVFile componentsSeparatedByString:@"\n"];

    NSArray *paColumnsOfRow;

    NSString *pstrFirstColumn;



    for(NSString * pstrRow in paRowsOfCSVFile)

    {

        paColumnsOfRow= [pstrRow componentsSeparatedByString:@","];

        pstrFirstColumn= [paColumnsOfRow objectAtIndex:0];

        if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame)

        {

            UIAlertView *alertingFileName = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

            [alertingFileName show];

            break;

        }

        else

        {

            UIAlertView *alertingFileName1 = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Not Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

            [alertingFileName1 show];

            break;

        }

    }


}

【问题讨论】:

    标签: ios xcode csv


    【解决方案1】:

    如果名字不匹配,您的 else 语句似乎会跳出 for 循环。如果您找到匹配项,您将需要删除它并可能添加一个变量来跟踪。仅当您匹配名称时才设置它。在 for 循环之后,检查变量以查看是否匹配。如果没有,则显示“未找到”的 UIAlertView。

    【讨论】:

    • 哦耶...我实际上尝试不使用 else 块本身...但它仍然只检查第一行第一列
    • [paRowsOfCSVFile 计数] 等于多少?如果它只有 1 并且你的文件有多行,你需要在“\r”而不是“\n”上分割吗?
    【解决方案2】:

    几个提示:

    1. 您只检查一列。

      if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame)
      

    对其他两列执行相同操作。然后您将解决您的第一个问题,即只检查一列。

    1. 看起来行终止符不正确。根据创建 csv 文件的平台,它可能有不同的行终止符。我建议使用像 notepad++ 这样的文本编辑器并查看隐藏代码以找出您的行终止符。然后使用终止符拆分行。确保您获得超过 1 行(仅输出 rows 变量)。

    【讨论】:

    • 如何检查多行?我尝试了 \n 和 \r 终止...我使用普通 nodepad 创建 csv 文件
    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多