在C分裂字符串 [英] splitting string in c

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

问题描述

我有一个文件,其中每行看起来是这样的:

I have a file where each line looks like this:

cc ssssssss,n

,其中两个第一'C的有个别人物,可能是空格,再经过一个空间,那么的的是一个字符串,长度为8个或9个字符,然后有一个逗号,然后一个整数。

where the two first 'c's are individual characters, possibly spaces, then a space after that, then the 's's are a string that is 8 or 9 characters long, then there's a comma and then an integer.

我真的很新的C,我试图找出如何将这个成每行4独立变量(每头两个字符,字符串,以及数)

I'm really new to c and I'm trying to figure out how to put this into 4 seperate variables per line (each of the first two characters, the string, and the number)

有什么建议?我看的fscanf和strtok的,但我不知道如何让他们对这项工作。

Any suggestions? I've looked at fscanf and strtok but i'm not sure how to make them work for this.

感谢您。

推荐答案

我假设这是一个C的问题,因为这个问题建议,而不是C ++作为标签也许建议。

I'm assuming this is a C question, as the question suggests, not C++ as the tags perhaps suggest.


  1. 阅读整行。

  1. Read the whole line in.

使用 和strchr 找到逗号。

Use strchr to find the comma.

你想与前两个字符什么的。

Do whatever you want with the first two characters.

切换为逗号零​​,标志着字符串的结束。

Switch the comma for a zero, marking the end of a string.

呼叫的strcpy 从提取 sssssss 部分第四个字符。

Call strcpy from the fourth character on to extract the sssssss part.

呼叫的atoi 过去那里的逗号是提取整数一个字符。

Call atoi on one character past where the comma was to extract the integer.

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

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