Convert space blank to tab - C String

C examples for String:char array

Description

Convert space blank to tab

Demo Code

#include <stdio.h>

#define MAXLINE 1000/* w w  w . j av a  2  s.  c  o m*/
#define TAB_WIDTH 8

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

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

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

    return 0;
}

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

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

Result


Related Tutorials