Wednesday, November 25, 2015

Limbajul C. "Insert a letter in string".

Fara prea multe comentarii (cu exceptia celor din cod :-), inca o problema din cursul de la University College Cork, menita sa fixeze notiuni precum siruri de caractere, tablouri, functii.

1.  Write and test a function that inserts a character anywhere in a string. The function should take the general form: strins(  char *string,  char character,  int position ).

Codul si printscreen-ul executiei:

#include <stdio.h>

/* The logical behind: once given the desired position in string for the new letter, every existent letter, starting from that index, should be right-shifted one position, so if the previous dimension of the string was n, the new dimension will be n + 1.
*/
           
int InsertLetter(char p[], int n, char c);

int main()
{
            char tab[81] = {"\0"}, c; // max 80 characters, not to mention '\0'
            int i = 0, j;
            puts("Gimmie a string to feed the array...\nEnd it with a tab if is less than 80 chars.");
            while(i < 80)
            {
                        tab[i] = getchar();
                        if(tab[i] == '\t')
                        {
                                    tab[i] = '\0';
                                    break;
                        }
                        else tab[i + 1] = '\0';
                        i++;
            }
            _flushall();
            puts("Now, gimmie a letter and an index. \nThe letter will be inserted in string to the specified position.\n");
            printf("The letter is: ");
            scanf("%c", &c);
            _flushall();
            printf("The index is: ");
            scanf("%d", &j);
            if(InsertLetter(tab, j, c)) printf("The modified string is:\n%s.\n", tab);
            return 0;
}

int InsertLetter(char p[], int n, char c)
{
            int l = 0, i;
            // we check the string dimension
            while(p[l++]);
            l--;; // we don't count the '\0'
            printf("Initial string dimension: %d.\n", l);
            if(l >= 80) // cannot insert at the very end
            {
                        printf("\nI can't make room for the %c letter.", c);
                        return 0;
            }
            else if(n > l)
            {
                        printf("\nI can't insert the %c letter at index %d.", c, n);
                        return 0;
            }
            else
            {
                        for(i = l - 1; i >= n; i--) p[i + 1] = p[i];
                        p[n] = c;
                        p[l + 1] = '\0';
            }          
            return 1;
}


No comments:

Post a Comment