OneBite.Dev - Coding blog in a bite size

slice a string in C

Code snippet on how to slice a string in C

#include <string.h>

/* define a pointer to the string to be sliced */
char* str = "Hello World";
 
/* define a pointer to the substring */
char* sub;
 
/* use strncpy to copy a substring from str to sub */
strncpy(sub, str, 5);

/* add a null terminator character to the end of the substring */
sub[5] = '\0';

This code shows how to slice a string in C. It begins by including the string.h header file, which provides functions for string manipulation, such as slicing and copying. Then it defines a pointer to the string to be sliced, for example, “Hello World”, and a pointer to the substring. After that, strncpy is used to copy a substring from the original string to the new substring. The first argument is the destination (the pointer to the substring) and the second argument is the source (the pointer to the original string). In this example, 5 is then specified as the number of characters to copy, which is the length of the substring. Finally, a null terminator character is added to the end of the substring using subscript notation. This marks the end of the substring so that C knows when to stop.

c