将字符串拆分为标记

时间:2014-04-02 22:32:19

标签: c token strtok

* 有人可以帮我这个功能。我正在尝试将字符串输入分成标记,并将每个标记移动一些指定的数量。 *

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;
}

1 个答案:

答案 0 :(得分:0)

据我所知,我认为这应该可以达到目的

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;
} 

产生:

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 

stringShift函数未更改