Function to determine how many items in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MajesTEK
    New Member
    • Aug 2008
    • 3

    Function to determine how many items in a string

    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.
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    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.(Becaus e 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).

    Comment

    • MajesTEK
      New Member
      • Aug 2008
      • 3

      #3
      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_a rray);b++)
      {
      if (c == ",") {
      conter++
      }
      };
      int finalcount = counter +1

      Comment

      • Savage
        Recognized Expert Top Contributor
        • Feb 2007
        • 1759

        #4
        Originally posted by MajesTEK
        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_a rray);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)

        Comment

        • edwardrsmith
          New Member
          • Feb 2008
          • 62

          #5
          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:

          [CODE=c]
          unsigned char *string_array;
          string_array = (char*)malloc(s izeof(unsigned char)*500);
          &string_array=" 10,100,10,120,1 00,10";

          int i, counter;
          unsigned char c;
          c = string_array[a]

          for (b=0; b < strlen(string_a rray); b++) {
          c = string_array[b];
          if (c == ",")
          conter++
          }

          int finalcount = counter +1[/CODE]

          Edward

          Comment

          • MajesTEK
            New Member
            • Aug 2008
            • 3

            #6
            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.

            Comment

            • edwardrsmith
              New Member
              • Feb 2008
              • 62

              #7
              Just to confuse you a little, in c strings are character arrays. It is just how you look at them. In other words

              Code:
              char str[500];
              Is the same as

              Code:
              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

              Comment

              • donbock
                Recognized Expert Top Contributor
                • Mar 2008
                • 2427

                #8
                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:
                Code:
                char array1[] = {1, 2, 3, 4};
                char array2[] = "1234";
                const char *parray3 = "1234";
                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:
                Code:
                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

                Comment

                • donbock
                  Recognized Expert Top Contributor
                  • Mar 2008
                  • 2427

                  #9
                  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

                  Comment

                  • weaknessforcats
                    Recognized Expert Expert
                    • Mar 2007
                    • 9214

                    #10
                    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.

                    Comment

                    • donbock
                      Recognized Expert Top Contributor
                      • Mar 2008
                      • 2427

                      #11
                      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.

                      Comment

                      • Mogrin
                        New Member
                        • Aug 2008
                        • 3

                        #12
                        You might be interested in the split method.
                        Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

                        Often times when I have simple parsing to do I use
                        Code:
                        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. :>

                        Comment

                        Working...