yrazlik
yrazlik

Reputation: 10787

Reading a string character by character in C

I am trying to read a string character by character in C. Since there is no string class, there are no functions to help this. Here is what i want to do: I have,

char m[80];  //I do some concenation, finally m is:

m= 12;256;2;

Now, i want to count how many characters are there between the semicolumns. In this example, there are 2,4 and 1 characters respectively. How can do this?

Thank you

Upvotes: 0

Views: 11490

Answers (3)

Daniel Santos
Daniel Santos

Reputation: 3295

If you don't mind modifying your string then the easiest way is to use strtok.

#include <string.h>
#include <stdio.h>
int main(void) {
    char m[80] = "12;256;2;";
    char *p;

    for (p = strtok(m, ";"); p; p = strtok(NULL, ";"))
        printf("%s = %u\n", p, strlen(p));
}

Upvotes: 1

Ambiguities
Ambiguities

Reputation: 415

Well I'm not sure were supposed to write the code for you here, just correct it. But...

int strcount, charcount = 0, numcharcount = 0, num_char[10] = 0;  
                                            //10 or how many segments you expect

for (strcount = 0; m[strcount] != '\0'; strcount++) {

    if (m[strcount] == ';') {

         num_char[numcharcount++] = charcount;
         charcount = 0;             

    } else {

         charcount++;

    }

}

This will store the amount of each character between the ; in an array. It is kind of sloppy I'll admit but it will work for what you asked.

Upvotes: 1

paddy
paddy

Reputation: 63481

What do you mean "there are no functions to help this"? There are. If you want to read a string, check out the function fgets.

On to the problem at hand, let's say you have this:

char m[80] = "12;256;2";

And you want to count the characters between the semi-colons. The easiest way is to use strchr.

char *p = m;
char *pend = m + strlen(m);
char *plast;
int count;

while( p != NULL ) {
    plast = p;
    p = strchr(p, ';');

    if( p != NULL ) {
        // Found a semi-colon.  Count characters and advance to next char.
        count = p - plast;
        p++;
    } else {
        // Found no semi-colon.  Count characters to the end of the string.
        count = pend - p;
    }

    printf( "Number of characters: %d\n", count );
}

Upvotes: 2

Related Questions