OneBite.Dev - Coding blog in a bite size

escape a string in C

Code snippet on how to escape a string in C

// Code to escape a string in C
#include <stdio.h>
#include <string.h>

void escape_string(char *str){
  int length = strlen(str);
  int i;

  for(i=0; i<length; i++){
    switch(str[i]) {
      case '\n':
        printf("\\n");
        break;
      case '\t':
        printf("\\t");
        break;
      case '\'':
        printf("\\'");
        break;
      default:
        putchar(str[i]);
        break;
    }
  }
  printf("\n");
}

This code sample is used to escape a string in the C programming language. It does this by looping through each character of the string and replacing it with the corresponding escaped character. For example, a line break would be replaced with ā€˜\nā€™ and a single quote would be replaced with '''. After looping through the entire string, it prints the escaped string in the console.

c