回答
为什么你会使用strcat()
是什么?所有你需要的是memmove()
:
void remove_char_at(char *str, unsigned int pos) {
memmove(str + pos, str + pos + 1, strlen(str) - pos);
}
这里是一个小例子程序我写了使用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;
}
请告诉我'newString'分配并不严重。获取任意长度输入时使用固定长度只是简单的不安全。 – ThiefMaster 2011-03-02 09:41:55
是的,但安全并不是这个例子的目标。我刚刚编写了一个快速示例,向他展示如何使用strcat删除角色。顺便说一句,我在回答中注明了这一点:需要添加额外的功能。 – red 2011-03-02 09:46:11
谢谢红色它非常有用 – onell 2011-03-03 11:20:10
- 1. 从字符串C#删除点字符
- 2. JQuery:从一个字符串中删除字符/选择
- 3. 从字符串中删除字符串
- 4. 从字符串中删除字符串
- 5. 从字符串中的某个字符中删除字符
- 6. 删除一个字符在字符串
- 7. Python:从第一个数字字符中删除字符串
- 8. C++从字符串中删除字符
- 9. 从字符串中删除字符
- 10. Python:从字符串中删除字符
- 11. 从字符串中删除字符
- 12. datagridview从字符串中删除'&'字符
- 13. jQuery从字符串中删除' - '字符
- 14. Fortran:从字符串中删除字符
- 15. 从字符串中删除Unicode字符
- 16. VB.NET - 从字符串中删除字符
- 17. 从c字符串中删除字符
- 18. C从字符串中删除字符
- 19. 从字符串中删除字符?
- 20. 从C字符串中删除字符
- 21. 从javascript中的另一个字符串中删除一个字符串
- 22. SQL Server的一个字符串中删除多个字符串
- 23. HiveQL:从字符串中删除句点
- 24. 可可 - 从字符串中删除所有字符并包括子字符串
- 25. 动态删除最后一个字符串后/从字符串
- 26. 从SQL字符串的字符删除
- 27. 删除字符串中的字符串
- 28. 如何从字符串[python]中删除一个字符?
- 29. 从八度字符串中删除第一个字符
- 30. 从字符串中删除一个字符
谢谢盗贼大师 – onell 2011-03-03 11:21:09
Upvoting/Accepting是一种更好的方式来表示感谢,而不是真的写下“谢谢”。 ;) – ThiefMaster 2011-03-03 12:01:29