在C中任意数量的空格上分割字符串 [英] Split string on any number of white spaces in C

查看:84
本文介绍了在C中任意数量的空格上分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中每个用户名和密码都用不同数量的空格分隔.

I have a file where each username and password is separated by a different number of white spaces.

bob    passowrd1
saly password2
sam      password2

void parse()
{
    FILE*open;
    open = fopen("file.txt");
    char line[101];
    char*name;
    char*password;

    while(fgets(100,line,open)!=NULL)
    {
       name = strtok(line,"*\\s");
       password = strtok(NULL,"*\\s");
       printf("username : %s",name);
       printf("password : %s",password); 
    }
}

我正在尝试使用strtok拆分字符串,但它不接受正则表达式作为分隔符.我能想到的唯一的其他方法是通过在字符串上循环并在空格后创建2个新的单独字符串来进行强行强制.有什么建议吗?

I'm trying to split the string using strtok but it doesn't accept regex as a delimeter. The only other way i can think of doing this is brute forcing by forlooping over the string and creating 2 new seperate strings after the whitespaces. any suggestions?

推荐答案

您(和大多数受访者)对此都过分考虑. strtok()在一个或多个定界符上定界,所以

You (and most of the respondents) are overthinking this. strtok() delimits on one or more of the delimiters, so

name = strtok(line," ");
password = strtok(NULL," ");

将完全按照您的要求进行操作.

will do exactly what you want.

这篇关于在C中任意数量的空格上分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆