gpt4 book ai didi

c - 将字符串拆分为标记

转载 作者:行者123 更新时间:2023-11-30 17:36:03 25 4
gpt4 key购买 nike

*有人可以帮我实现这个功能吗?我试图将字符串输入分成标记,并将每个标记移动一些指定的量。 *

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

最佳答案

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

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 函数不变

关于c - 将字符串拆分为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com