OneBite.Dev - Coding blog in a bite size

cut a string in C

Code snippet on how to cut a string in C

  char *str_cut(char *str, int begin, int len) { 
      char *str_part = (char *)malloc(sizeof(char) * len + 1);
      int c;
 
      for (c = 0 ; c < len ; c++) {
        str_part[c] = str[begin+c]; 
    } 
    str_part[c] = '\0'; 
    return str_part; 
  }

This code extracts a substring from a given string. The code takes three parameters: a pointer (called ‘str’) to the string we want to extract from, the index of the character from which to begin extraction (called ‘begin’), and how many characters to extract (called ‘len’). It creates a new string, which is allocated memory to store ‘len’ characters, then copies the characters from the specified index of the original string to the new string. The last character of the new string is set to a null character (‘\0’) to mark the end of string. Finally, the memory address of the new string is returned.

c