0

我想从 c 语言中字符串的可选点中删除一个字符。我想通过指针和 strcat() 函数编写这个程序。请指导我

谢谢大家

4

2 回答 2

0

这是我编写的一个小示例程序,用于使用strcat. 我在评论中解释了步骤。

您可能需要添加一些额外的功能,例如检查pos >= 0 && pos < strlen(string).

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

char *removeCharacter(char *string, int pos);

int main(void) {
   char string[] = "Testing strings"; // The string to remove chars from
   char *newString; // The resulting string

   newString = removeCharacter(string, 3);
   printf("Result is '%s'\n", newString); // Print result

   free(newString); // Clean up allocated memory for the resulting string.

   return 0;
}

char *removeCharacter(char *string, int pos) {
   char buffer[255]; // Temporary storage for the beginning of the string
   char *appendix = string + (pos + 1); // Appendix (rest of the string without omitted character)
   char *newString = (char *)malloc(255 * (sizeof(char))); // Allocate some memory for the resulting string

   printf("Copying %d chars from %s to buffer...\n", pos, string);
   strncpy(buffer, string, pos); // Copy pos characters from string to buffer (our beginning of the string)
   buffer[pos] = '\0'; // Don't forget to add a NULL byte to indicate the end of the string

   printf("Buffer is '%s' and appendix is '%s'\n", buffer, appendix);
   strcat(newString, buffer); // Concatenate buffer (beginning) and appendix (ending without character)
   strcat(newString, appendix);

   return newString;
}
于 2011-03-02T08:20:29.297 回答
0

你为什么要使用strcat()它?您只需要memmove()

void remove_char_at(char *str, unsigned int pos) {
    memmove(str + pos, str + pos + 1, strlen(str) - pos);
}

演示:http ://codepad.org/SrgzQohD

于 2011-03-02T07:58:17.947 回答