Pregunta

*Can someone please help me with this function. I'm trying to separate the string input into tokens and also shift each token some by some specified amount. *

char *tokenize(char *f, int shift){

    const char delim[] = " .;\n\t";
    char *pa = f;   //points to the beginning of *f

    //size of *f
    int i;
    int stringSize = 0;
    for(i = 0; f[i] != '\0'; i++)
    {
       stringSize++;
    }

    //put string in array to pass to strtok function  
    char newString[stringSize]; 
    int j;
    for(j = 0; j < stringSize; j++)
    {
        newString[j] = *f;
        f++;
    }

    //break the words up into sub-strings without the delimiters 
    char *word = strtok(newString, delim);  

    while(word != NULL)
    {
        word = strtok(NULL, delim);
        word = stringShift(word, shift); 
        //printf("After being shifted %d = %s\n", shift, word);
    }

    return pa;
} 

/*Shift Function*/

char *stringShift(char *s, int k){

    int i;

    for(i = 0; s[i] != '\0'; i++)
    {
        s[i] += k;
    }

    return s;
}
¿Fue útil?

Solución

I think this should serve the purpose ok, as far as I understand it

char* addWordToArr(char *arr,char *word)
{
    int i;

    for(i =0;i<strlen(word);i++)
    {
        *arr++ = word[i];
    }
    *arr++ = ' ';

    return arr;
}

char *tokenize(char *f, int shift){

    const char delim[] = " .;\n\t";

    int stringSize = strlen(f);

    //put string in array to pass to strtok function  
    char newString[stringSize+1]; 
    int j;
    for(j = 0; j < stringSize; j++)
    {
        newString[j] = *f;
        f++;
    }

    newString[stringSize] = '\0'; //null terminate

    char *rVal = malloc(sizeof(char) * (stringSize +1)); //The total length of the tokenized string must be <= the original string

    char *writePtr = rVal;

    //break the words up into sub-strings without the delimiters 
    char *word = strtok(newString, delim);  
    word = stringShift(word, shift); 
    writePtr = addWordToArr(writePtr,word);

    while(word != NULL)
    {

        word = strtok(NULL, delim);
        if(word)
        {
            word = stringShift(word, shift); 
            writePtr = addWordToArr(writePtr,word);

        }

    }

    writePtr = '\0';

    return rVal;
} 

which produces:

string before shift bish;bash;bosh hyena trout llama exquisite underwater dinosaur
string after shift dkuj dcuj dquj j{gpc vtqwv nncoc gzswkukvg wpfgtycvgt fkpqucwt 

The stringShift function is unchanged

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top