用于确定字符串中有多少项的函数 [英] Function to determine how many items in a string

查看:74
本文介绍了用于确定字符串中有多少项的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我是C编程的新手并尝试做点什么。


我有一个字符串。它只是用逗号分隔的数字。


示例。


unsigned char string [] = {1,2,3,4,5 ,6};



我需要计算有多少项目。这是一个需要知道它获得了多少项的函数。有更多的字符串,所以它不是固定的值。而且我不能只使用最大可能。我知道我需要使用string.h函数...我的理解是我会做类似的事情:


得到整个字符串的长度。

看起来对于第一个逗号

添加到计数器变量。

寻找下一个,重复到结束。

可以有人给我一个代码示例?


或者有更简单的方法我会帮助任何帮助。

谢谢。

Hi everyone,

I''m new to C programming and trying to do something.

I have a character string. Its just numbers delimited by a comma.

Example.

unsigned char string[] = {1,2,3,4,5,6};


I need to count how many items there are. This is for a function that needs to know how many items its getting. There are more strings so Its not a fixed value. And I can''t just use a maximum possible. I know I need to use string.h functions... my understanding is that I would do something like:

get length of whole string.
look for first comma
add to counter variable.
look for next, repeat till end.
can some one give me an example of the code?

or of there is an easier way I would appritiate any help.
Thanks.

推荐答案

只有在string.h中声明的你需要使用的函数是strlen,它返回不计算字符串结尾的字符串的长度。所以只做一个简单的for循环,你将比较当前索引的值和值逗号,如果它匹配增加计数器。(因为元素的数量是逗号的数量+ 1,你需要迟早将一个添加到计数器变量,所以最好将它初始化为1)。
Only function you need to use that is declared in string.h is strlen which returns length of the string not counting end of string character.So just make a simple for loop in which you will compare value at current index with value of comma,if it matches increase the counter.(Because number of elements is number of commas +1,you will need to add one to the counter variable sooner or later,so better initialize it to 1).


啊,确实有效。所以类似



unsigned char string_raray [] = {10,100,10,120,100,10};


int a,b,计数器;

a = 0;

c = string_array [a]


for(b = 0; b< strlen(string_array) );; b ++)

{

if(c ==","){

conter ++

}

};

int finalcount = counter +1
ahh ok that works. So something like


unsigned char string_raray[] = {10,100,10,120,100,10};

int a,b,counter;
a = 0;
c = string_array[a]

for (b=0;b < strlen(string_array);b++)
{
if (c == ",") {
conter++
}
};
int finalcount = counter +1



ahh ok这样可行。所以类似



unsigned char string_raray [] = {10,100,10,120,100,10};


int a,b,计数器;

a = 0;

c = string_array [a]


for(b = 0; b< strlen(string_array) );; b ++)

{

if(c ==","){

conter ++

}

};

int finalcount = counter +1
ahh ok that works. So something like


unsigned char string_raray[] = {10,100,10,120,100,10};

int a,b,counter;
a = 0;
c = string_array[a]

for (b=0;b < strlen(string_array);b++)
{
if (c == ",") {
conter++
}
};
int finalcount = counter +1



不,如果与string_array比较,请更改c in [b]。(你不需要a和c,但你需要定义反变量)

Nope,change c in if comparison to string_array[b].(And you don''t need a and c,but you do need counter variable defined)


这篇关于用于确定字符串中有多少项的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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