2

I'm trying to implement question 8.13 from C How to program, which is simply shifting left from the second char of the string and concat the first char of the string with "ay". For example:

jump -> umpjay the -> hetay and so on.

My try is here:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *appender(char s);
void shiftLeft(char [], int);

int main()
{
    char s[100], *lastThree;
    
    fgets(s, 100, stdin);
    s[strcspn(s, "\n")] = 0;
    char *tokenPtr = strtok(s, " ");

    while(tokenPtr != NULL){
        
        lastThree = appender(tokenPtr[0]);
        //printf("lastThree : %s\n", lastThree); //for debugging
        
        shiftLeft(tokenPtr, strlen(tokenPtr));
        
        sprintf(tokenPtr, "%s%s ", tokenPtr, lastThree); // concatenation
        
        
        printf("tokenptr:%s ", tokenPtr);
        tokenPtr = strtok(NULL, " ");
    }
    
    
    return 0;
}

char *appender(char s){
    char *returned = (char*)malloc(sizeof(char)*4); // allocation
    snprintf(returned, sizeof(returned), "%c%s",s,"ay"); // append ay
    return returned;
}

void shiftLeft(char s[], int len){
    int i;
    for(i=0;i<len-1;i++){
        s[i]=s[i+1];
    }
    s[i] = '\0';
}

But code works wrong. It evaluates tokenPtr as yaay even if the input is only a word.

akoluacik
  • 33
  • 5
  • @jarmod, if you meant the function, I need to get first element of the char and add it to end of the string with "ay". – akoluacik Aug 31 '21 at 07:23
  • @user2121023 is there any function I can use? I used strcat but it didn't work well either. – akoluacik Aug 31 '21 at 07:25

0 Answers0