如何将字符附加到字符串上?
How to append a character onto a string?
我在 Stack Overflow 上看到的示例与我的问题很接近,但其中 none 似乎匹配,所以我不得不问自己:如何正确地将字符附加到字符串在C?我知道 strcat() 不能完成这项工作,使用数组值也不能正常工作。这是我的代码:
char* buildWord(int posX, int posY, int nextX, int nextY, int gridX, int gridY, char** grid, char* str, int length){
int len2;
char* word = malloc(sizeof(char) * 20);
if(posX+nextX < 0 || posX+nextX > gridX)
return NULL;
if(posY+nextY < 0 || posY+nextY > gridX)
return NULL;
strcpy(word, str);
len2 = strlen(word);
word[len2 + 1] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 2] = '[=10=]'; //single character
printf("%s", word);
length++;
if(length < 4)
word = buildWord(posX+nextX, posY+nextY, nextX, nextY, gridX, gridY, grid, word, length);
return word;
}
正如您可能猜到的那样,此代码的目的是根据特定方向的字母网格构建字符串(类似于单词搜索)。例如,如果我的初始字符串 "str" 是 "c" 并且沿着对角线方向前进,下一个字母是 "a",那么我想要放在一起的字符串是 "ca"。
当我运行这段代码时,没有附加字母。该字符串在整个代码中保持不变,这当然会导致它中断。有正确的方法吗?
你这里有一个错误:
word[len2 + 1] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 2] = '[=10=]';
应该是:
word[len2] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 1] = '[=11=]';
记住索引以0
开头
我在 Stack Overflow 上看到的示例与我的问题很接近,但其中 none 似乎匹配,所以我不得不问自己:如何正确地将字符附加到字符串在C?我知道 strcat() 不能完成这项工作,使用数组值也不能正常工作。这是我的代码:
char* buildWord(int posX, int posY, int nextX, int nextY, int gridX, int gridY, char** grid, char* str, int length){
int len2;
char* word = malloc(sizeof(char) * 20);
if(posX+nextX < 0 || posX+nextX > gridX)
return NULL;
if(posY+nextY < 0 || posY+nextY > gridX)
return NULL;
strcpy(word, str);
len2 = strlen(word);
word[len2 + 1] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 2] = '[=10=]'; //single character
printf("%s", word);
length++;
if(length < 4)
word = buildWord(posX+nextX, posY+nextY, nextX, nextY, gridX, gridY, grid, word, length);
return word;
}
正如您可能猜到的那样,此代码的目的是根据特定方向的字母网格构建字符串(类似于单词搜索)。例如,如果我的初始字符串 "str" 是 "c" 并且沿着对角线方向前进,下一个字母是 "a",那么我想要放在一起的字符串是 "ca"。
当我运行这段代码时,没有附加字母。该字符串在整个代码中保持不变,这当然会导致它中断。有正确的方法吗?
你这里有一个错误:
word[len2 + 1] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 2] = '[=10=]';
应该是:
word[len2] = grid[posX + nextX][posY + nextY]; //grid[x][y] represents a
word[len2 + 1] = '[=11=]';
记住索引以0