Skip to content

Instantly share code, notes, and snippets.

@joegasewicz
Last active November 25, 2022 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegasewicz/9221a2c4ea73b422e54eea839420395a to your computer and use it in GitHub Desktop.
Save joegasewicz/9221a2c4ea73b422e54eea839420395a to your computer and use it in GitHub Desktop.
Count the length of a string in C
#include <stdio.h>
#include <stdlib.h>
int calc_len_str(const char *str);
int main()
{
char str[] = "How are you today!";
int result = calc_len_str(str);
printf("result 1 = %d\n", result);
if (result != 18)
return 1;
int result2 = calc_len_str2(str);
if (result2 != 18)
return 1;
printf("result 2 = %d\n", result2);
return 0;
}
int calc_len_str(const char *str)
{
int count = 0;
while(*str)
{
*str++;
count++;
}
return count;
}
int calc_len_str2(const char *str)
{
const char *lastAddr = str;
while(*lastAddr)
*lastAddr++;
return lastAddr - str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment