Post

String Helper Functions

String Helper Functions

String Helper Functions

let’s do a quick recap of important C string helper functions from <string.h>. These are the ones you’ll actually use a lot in firmware / interviews.


1. String Length

1
size_t strlen(const char *str);

Returns length of string (not counting \0).

1
2
char s[] = "Hello";
printf("%zu\n", strlen(s));  // 5

2. Copying Strings

1
2
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);

strcpy copies whole string, strncpy limits to n chars.

1
2
3
char src[] = "World";
char dest[10];
strcpy(dest, src);   // dest = "World"

Be careful: strcpy can overflow buffer. Use strncpy for safety.


3. Concatenation

1
2
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);

Appends src to dest.

1
2
char s[20] = "Hello ";
strcat(s, "World");  // s = "Hello World"

4. Comparison

1
2
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);

Returns 0 if equal, <0 if s1<s2, >0 if s1>s2.

1
2
printf("%d\n", strcmp("abc","abc")); // 0
printf("%d\n", strcmp("abc","abd")); // -1

  • Find first occurrence of character:
1
char *strchr(const char *str, int c);
1
char *p = strchr("hello", 'e'); // points to "ello"
  • Find last occurrence of character:
1
char *strrchr(const char *str, int c);
  • Find substring:
1
char *strstr(const char *haystack, const char *needle);
1
char *p = strstr("hello world", "world"); // points to "world"

6. Tokenize

1
char *strtok(char *str, const char *delim);

Splits string into tokens.

1
2
3
4
5
6
char s[] = "red,green,blue";
char *token = strtok(s, ",");
while (token != NULL) {
    printf("%s\n", token);
    token = strtok(NULL, ",");
}

Output:

1
2
3
red
green
blue

7. Memory Helpers

These work on raw memory, not just strings:

1
2
3
4
void *memcpy(void *dest, const void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
void *memset(void *str, int c, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
  • memcpy – fast copy (no overlap).
  • memmove – safe copy (handles overlap).
  • memset – fill memory with value.
  • memcmp – compare memory blocks.

Quick Tricks:

  • Use strlen + strcpy/strncpy to duplicate.
  • Use strtok to parse UART strings / CSV.
  • Use memset to clear structs (memset(&myStruct, 0, sizeof(myStruct))).
  • Use strstr to detect commands (if (strstr(rxBuffer, "START")) { ... }).

This post is licensed under CC BY 4.0 by the author.