473,473 Members | 4,297 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Function to determine how many items in a string

3 New Member
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.
Aug 8 '08 #1
11 1924
Savage
1,764 Recognized Expert Top Contributor
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).
Aug 8 '08 #2
MajesTEK
3 New Member
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
Aug 8 '08 #3
Savage
1,764 Recognized Expert Top Contributor
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
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)
Aug 8 '08 #4
edwardrsmith
62 New Member
I may be wrong on this as most of the time when I deal with arrays I use pointers but I think that the array you are assigning to the unsigned char array is an array of numbers. If you are truly using a string it should be surounded in quotes. Instead what you are doing is passing an array with the numbers only. In this case the commas are not transfered into the array but are instead only used to seperate the items. A more apropriate example would look like this:

Expand|Select|Wrap|Line Numbers
  1. unsigned char *string_array;
  2. string_array = (char*)malloc(sizeof(unsigned char)*500);
  3. &string_array="10,100,10,120,100,10";
  4.  
  5. int i, counter;
  6. unsigned char c;
  7. c = string_array[a]
  8.  
  9. for (b=0; b < strlen(string_array); b++) {
  10.     c = string_array[b];
  11.     if (c == ",")
  12.         conter++
  13. }
  14.  
  15. int finalcount = counter +1
Edward
Aug 8 '08 #5
MajesTEK
3 New Member
Hi Edward,

Yes your right, I am using a character array, not character string. Im in process of wrapping my head around the array manipulation, so I mistakenly call arrays of characters as strings. I will start paying more attention to that. Thank you for the input and the code example. Could you provide the same but for the manipulation of the array. It seems my code would work with the changes suggested. I will try that. Thank you everyone.
Aug 8 '08 #6
edwardrsmith
62 New Member
Just to confuse you a little, in c strings are character arrays. It is just how you look at them. In other words

Expand|Select|Wrap|Line Numbers
  1. char str[500];
Is the same as

Expand|Select|Wrap|Line Numbers
  1. char *str = (char*)malloc(sizeof(char)*500);
Technically the first is a character array while the second one is as close as c comes to a "string". Both are used often and personally, I prefer the second though it requires a bit of clean up (look at the "free" function if you are curious).

Edward
Aug 8 '08 #7
donbock
2,426 Recognized Expert Top Contributor
I assume you want to know how many elements are in the array, rather than the amount of storage consumed by the array.

Compare these declarations:
Expand|Select|Wrap|Line Numbers
  1. char array1[] = {1, 2, 3, 4};
  2. char array2[] = "1234";
  3. const char *parray3 = "1234";
  4. const char *parray4 = {1, 2, 3, 4};
The first declares array1 as an array of 4 char's: 1, 2, 3, 4. The number of elements in the array is intrinsic to the type of array1.

The second declares array2 as an array of 5 char's: '1', '2', '3', '4', 0. The number of elements in the array is intrinsic to the type of array2. (Reminder: '1' is the character "1", not the number "1".)

The third declares parray3 as a pointer to the start of an array of 5 char's: '1', '2', '3', '4', 0. This array is stored somewhere in memory, you really don't control where. The type of parray3 carries no information about the number of elements in the array.

I don't recall ever trying a declaration like the fourth one, but let's assume it is legal. If so, then it declares parray4 as a pointer to the start of an array of 4 char's: 1, 2, 3, 4. This array is stored somewhere in memory, you really don't control where. The type of parray4 carries no information about the number of elements in the array.

sizeof(array1) returns the amount of storage consumed by the array in char's. That's the same as the number of elements in a char array. What if you had defined array1 as an array of short's? Assume the size of a short is twice that of a char -- then sizeof(array1) would return twice the number of entries in the array -- the wrong answer. Can you think of a way to use sizeof() that will always give you the number of elements in an array regardless of the size of each element in the array? [Yes, there is a common C idiom for doing this!]

I can't think of any reliable/portable way to find the number of elements in the array pointed to by parray4.

Notice that array2 and the array pointed to by parray3 are strings. That means you can use strlen() to find the lengths of those strings. Notice that the length of a string is one less than the number of elements in the array (the terminating 0 isn't counted in the string length).

Notice that array1 and the array pointed to by parray4 are NOT strings. That means that very bad things could happen if you tried to use strlen() on them. You might simply get a wrong answer; or your program might halt and dump core. Be afraid, be very afraid.

Here's one last wrinkle:
Expand|Select|Wrap|Line Numbers
  1. char array5[10] = "1234";
This declares an array of 10 char's: '1', '2', '3', '4', 0, 0, 0, 0, 0, 0. In this case the number of elements in the array is 10, but the length of the string is 4.

Cheers,
Don
Aug 8 '08 #8
donbock
2,426 Recognized Expert Top Contributor
Are you using C or C++?

With C, your only option is the sizeof() idiom that I alluded to earlier.

With C++, you can use the same sizeof() trick as C or you can do something much fancier involving templates. C++ isn't my cup of tea, so somebody else would have to help you with that.

By the way, I learned of the C++ template trick by doing a quick Google search. That search also yielded the sizeof() trick that I already knew about.

Cheers,
Don
Aug 8 '08 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
Be very careful about using sizeof to get the size of an array. This only works when the array is a local variable, that is , on the stack.

It it's on the heap, or passed to a function ans you do sizeof inside the function, you always get 4 because only the address is passed.

I assume everyone has read: http://bytes.com/forum/thread772412.html.
Aug 10 '08 #10
donbock
2,426 Recognized Expert Top Contributor
Be very careful about using sizeof to get the size of an array. This only works when the array is a local variable, that is , on the stack.

It it's on the heap, or passed to a function ans you do sizeof inside the function, you always get 4 because only the address is passed.
Yes. In fact this answers the question "What is the difference between a pointer and an array." In most ways, they can be used interchangeably. How they react to sizeof is one of the few ways they are different.
Aug 11 '08 #11
Mogrin
3 New Member
You might be interested in the split method.
http://msdn.microsoft.com/en-us/libr...6a(VS.80).aspx
Often times when I have simple parsing to do I use
Expand|Select|Wrap|Line Numbers
  1. string [] splitStr = str.Split(new char [] {','});
The same method is supported in c++ but I don't know if you're using .net or not. :>
Aug 11 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my...
5
by: JT | last post by:
how do i determine how many items are in an array? the following code creates an array of values each time a space is found in a name field. the problem is that sometimes names have middle...
4
by: sara | last post by:
I've gotten my first function to work - to build a sql string to load a list box. I call the function whenever I want the list box loaded 1. When a customer is chosen - opens the frmCust and...
6
by: SStory | last post by:
Can anyone tell me what algorithm I should use to determine how many tabs to add to a string. I have two strings. I want to add them to a listbox concatenated but with a tab between them. ...
0
by: kagorami | last post by:
Q: How do you return a LPSTR from unmanaged code? A: Use a StringBuilder. What about this: public struct CSTRUCT { string return_value; } How do you get a LPSTR from unmanaged code when it...
1
by: joshua siew | last post by:
Dear all who is nice, I'm the DUMBEST person on earth who just started to use VC++.... need some help on the below coding....please check the NOTE section.... thanks in advanced... ...
11
by: google | last post by:
I need a simple wildcard pattern matching function written in JS. I have wrestled with regular expresions but frankly am struggling to come up with anything less than an epic function of many lines...
1
by: bassi.carlo | last post by:
I have an application with many combobox in different forms used for choose a particular length (for example items are "ft" - feet, "in" - inch, "m" - meters, and so on). I don't want to put in...
1
by: speranza | last post by:
i have multiple checkboxes on my form.i am trying to add them with stored procedure but it gives me Procedure or function konut_ekle has too many arguments specified protected void...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.