0

if anyone has ever wanted to try and rewrite a string function in C, would this code work to replace the standard strlen() function? I have not been able to run this code because I am sitting in my car typing it on my iPhone.

int strlen(char * s) {
      int i = 0, sum = 0;
      char c = s[0];

      while(c != '\0') {
            sum++;
            c = s[++i];
      }
      return sum;
}

You feedback is so much appreciated!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Only change the name since the real function have the same name! Also whats the question here? you started a question and not a blog! – Rizier123 Nov 14 '14 at 04:54
  • 2
    `strlen` returns `size_t`. From the performance point of view, your function has much more to do to beat the standard function. Read [How the glibc strlen() implementation works](http://stackoverflow.com/questions/20021066/how-the-glibc-strlen-implementation-works) – Yu Hao Nov 14 '14 at 05:02
  • 1
    Ask code review functions on [Code Review](http://codereview.stackexchange.com/). – Yu Hao Nov 14 '14 at 05:03
  • 1
    Is your car moving? If it is, I suggest that you stop programming. – Martin James Nov 14 '14 at 06:08
  • 3
    This question appears to be off-topic because it is about code review. – n. m. could be an AI Nov 14 '14 at 07:48
  • On entering and exiting the `while` loop, both `i` and `sum` always have the same value. Removing `i` and `sum++;`, as well as replacing `c = s[++i];` with `c = s[++sum];` doesn't change the algorithm. Since you are typing this on a cell phone you should probably also replace `sum` with `l` to save on keystrokes. And btw, are you telling me that you cannot run a C compiler on your iPhone? Doesn't that make it somewhat shitty for a developer? Then again, Steve never was one, so why care about developers. – IInspectable Mar 03 '17 at 11:45

6 Answers6

6

If you want to rewrite standard C function strlen then you should follow the declaration conventions of the function.

size_t strlen(const char *s);

First of all it should have return type size_t and the parameter shall have qualifier const that you could use the function with constant character arrays. Also such a name as sum is not very suitable for this function. In your function you have too many local variables.

I would write the function the following way

size_t strlen( const char *s ) 
{
    size_t n = 0;

    while ( s[n] ) ++n;

    return n;
}

The other way is to use only pointers. For example

size_t strlen( const char *s ) 
{
    const char *p = s;

    while ( *p ) ++p;

    return p - s;
}
autistic
  • 1
  • 3
  • 35
  • 80
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Looks like it would work, but you don't need 2 integers, so it's overly complex. [] lookup might be slow - pointer manipulation might be faster.

int myStrlen(char *s)
{
    int len = 0;
    while(*s != 0) {
        s++;
        len++;
    }
    return len;
}
John3136
  • 28,809
  • 4
  • 51
  • 69
1

There's no need for an int counter.

size_t myStrlen(char *s)
{
 char *e=s;
 while(*e!='\0')e++;
 return e-s;
}
doog abides
  • 2,270
  • 16
  • 13
0

It should work. While the function can be optimized. Something like

 int my_strlen(char *s) {
    int sum = 0;
    while (*s++) sum++;
    return sum;
 }
Déjà vu
  • 28,223
  • 6
  • 72
  • 100
0

Here are different methods to write down code for strlen:

Without Using Pointers:

int mystrlen(char s[]) {

int i = 0;

while (s[i]!='\0')
 {
  i++;
 }

return i;

}

With Pointers:

int strlength(char const *s) {

int l=0;                                                    

while(*s1!='\0')                                      
{
  l++;
  s++;
}

return l;                                              

}

Without Counter:

int my_strlen(char const *s) {

char *p=s;

while(*p!='\0')
     p++;

return(p-s);

}

Using Recursion :

int mystrlen(char const *s) {

 if(*s==0) 
      return 0;

 return mystrlen(s+1)+1;

}

sv1
  • 57
  • 1
  • 2
  • 11
-2

The actual functionality is much more than what you have written.

  • Consider a scenario, where you have allocated a size of 100 to your pointer. And you forgot to add the '\0' as the last char for your array. How are you going to handle this situation? You cannot keep on incrementing the counter and keep looking for '\0'

  • Arrays have a max size. Your pointer string length function should also have a realistic length. you cannot keep on iterating the counter and look for '\0'. What if you enter another processes memory location and you start reading and writing to that application memory? You would end up messing multiple applications.

  • Depending on the type of compiler, it may or may not allocate memory sequentially. How are you going to handle this situation?

In short, you should work on malloc/new first. Understand it end to end and then try working on this.

kris123456
  • 501
  • 1
  • 5
  • 15
  • 2
    Bounds-checking isn't normally done with C arrays and strings... it's up to the programmer to keep track. Crashes from calling `strlen()` on unterminated strings aren't particularly rare even without a home-rolled function. – Dmitri Nov 14 '14 at 05:22
  • 1
    A _string_ in C _always_ has a terminating `'\0'`, else it is not a string. OP said "string function", so `char * s` always points to memory with a terminating `'\0'`. OTOH, OP could have asked for the length of a `char` array with a limit as this answer proposes. Not a bad idea, but then the function name should not be `str..()` – chux - Reinstate Monica Nov 14 '14 at 06:31
  • if i create a char array and if i do not give the last char as '\0' then the compiler throws relevant warnings when i try to access out of the allocated memory. How is it attained without handlig? – kris123456 Nov 16 '14 at 05:43
  • 1
    @kris123456 If `strlen()` were doing bounds-checking, it'd give a runtime error, not a compiler error... but it can't be, since the array length isn't available to it at runtime. Functions that do use the array length need to have it passed explicitly as an additional parameter (which isn't done for `strlen()` or most other string functions in C). – Dmitri Nov 16 '14 at 07:37