Home > database >  How to count characters in a C_String in C ?
How to count characters in a C_String in C ?

Time:02-28

I'm a new Computer Science student, and I have a homework question that is as follows:

Write a Function that passes in a C-String and using a pointer determine the number of chars in the string.

Here is my code:

#include <iostream>
#include <string.h>
using namespace std;
const int SIZE = 40;

int function(const char* , int, int);

int main()
{
     char thing[SIZE];
     int chars = 0;

     cout << "enter string. max " << SIZE - 1 << " characters" << endl;
     cin.getline(thing, SIZE);
     int y = function(thing, chars, SIZE);
     cout << y;
}


int function(const char *ptr, int a, int b){
    a = 0;
    for (int i = 0; i < b; i  ){
        while (*ptr != '\0'){
            a  ;
        }
    }
    return a;
}

CodePudding user response:

First of all welcome to stackoverflow ye0123! I think you are trying to rewrite the strlen() function here. Try giving the following link a look Find the size of a string pointed by a pointer. The short answer is that you can use the strlen() function to find the length of your string. The code for your function will look something like this:

int function(const char *ptr) 
{
    size_t length = strlen(ptr);
    return length;
}

You should also only need this function and main.

Edit: Maybe I misunderstood your question and you are supposed to reinvent strlen() after all. In that case, you can do it like so:

unsigned int my_strlen(const char *p)
{
    unsigned int count = 0;

    while(*p != '\0') 
    {
        count  ;
        p  ;
    }
    return count;
}

Here I am comparing *p from '\0' as '\0' is the null termination character.

This was taken from https://overiq.com/c-programming-101/the-strlen-function-in-c/

  • Related