Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best alternative to calling strlen() in my for loop condition in C?

Tags:

c

string

for-loop

I've read that it is bad practice to call strlen() in my for loop condition, because this is an O(N) operation.

However, when looking at alternatives I see two possible solutions:

int len = strlen(somestring);  
for(int i = 0; i < len; i++)  
{

}

or...

for(int i = 0; somestring[i] != '\0'; i++)  
{

}

Now, the second option seems like it might have the advantage of 1) not declaring an unnecessary variable, and 2) should the string length be modified in the loop it should still reach the end as long as the length isn't < i.

However, I'm not sure. Which one of these is standard practice among C programmers?

like image 951
Mithrax Avatar asked Mar 03 '10 17:03

Mithrax


People also ask

What can I use instead of strlen in C?

strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).

What is the use of strlen () method in C?

C strlen() The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type). It is defined in the <string.

What is the syntax of strlen ()?

The syntax of the strlen() function is: strlen(const char* str); Here, str is the string whose length we need to find out, which is casted to a const char* .

Can we use strlen in C?

The strlen() function in C is used to calculate the length of a string. Note: strlen() calculates the length of a string up to, but not including, the terminating null character. Return Value: The function returns the length of the string passed to it.


2 Answers

The second one is usually preferred.

The other popular form is

for (char* p = something; *p; p++)
{
   // ... work with *p
}

Yet another one is

char* p = something;
char c;
while ((c = *p++))
{
    // ... do something with c
}

(the extra () around assignment are needed to make some suspicious compilers not issue a warning stating I might mean comparison inside while condition)

Indeed, strlen is quite slow, because it must go through the whole string looking for trailing 0. So, strlen is essentially implemented as

int s = 0;
while (*p++) s++;
return s;

(well, in fact a slightly more optimized assembler version is used).

So you ought to avoid using strlen if possible.

like image 139
Vlad Avatar answered Oct 21 '22 04:10

Vlad


These are preferred:

for (int i = 0; str[i]; ++i)
for (char* p = str; *p; ++p)
like image 28
Tronic Avatar answered Oct 21 '22 04:10

Tronic