Replaces tabs in the input with the blanks space - C String

C examples for String:String Function

Description

Replaces tabs in the input with the blanks space

Demo Code

#include <stdio.h>

#define MAXLINE 1000/*w  ww. j  a v  a2 s  .  c  om*/
#define TAB_WIDTH 4

void detab(char s1[], char s2[], int tabwidth);

int main(void){
    char s1[MAXLINE] = "\this is a \tes\t";
    char s2[MAXLINE];

    detab(s1, s2, TAB_WIDTH);
    printf("detab result:\n%s\n", s2);

    return 0;
}

// copy characters in s1 to s2 and replace tabs with proper number of blanks
void detab(char s1[], char s2[], int w)
{
    int i, j, l, c, blanks;

    i = 0;
    l = 0;
    while ((c = s1[i++]) != '\0') {
        if (c == '\t') {
            blanks = w - l % w;
            for (j = 0; j < blanks; ++j)
                s2[l++] = ' ';
        } else {
            s2[l++] = c;
        }
    }
    s2[l] = '\0';
}

Result


Related Tutorials