从 C 中的字符串中删除字符 [英] Remove characters from a string in C
问题描述
我只能访问 'C' 并且需要替换字符数组中的字符.对于这个相对简单的过程,我还没有想出任何干净的解决方案.
I only have access to 'C' and need to replace characters within a character array. I have not come up with any clean solutions for this relatively simple procedure.
我传递了一个字符数组,例如:
I am passed a character array, for example:
char strBuffer[] = "/html/scorm12/course/course_index.jsp?user_id=100000232&course_id=100000879&course_prefix=ACQ&version=2&scorm_version=3&roster_id=100011365&course_name=Test%20Course%201.2&mode=browse&course_number=0000&mode_id=1";
我需要修改此缓冲区以将所有 &
替换为 &
.生成的缓冲区不必覆盖 strBuffer(可以创建新缓冲区).
I need to modify this buffer to replace all the &
with &
. The resulting buffer does not have to overwrite strBuffer (a new buffer can be created).
有什么建议吗?
过去我在循环中完成了 strstr 函数,但正在寻找一个更简单的解决方案,也许 C 等效于 String.Replace 方法.
In the past I have done the strstr function in a loop, but was looking for a simpler solution, perhaps the C equivalent to the String.Replace method.
对于我的迫切需要,以下是我所需要的.
For my immediate needs, the following is all that I need.
char strBuffer[] = "/html/scorm12/course/course_index.jsp?user_id=100000232&course_id=100000879&course_prefix=ACQ&version=2&scorm_version=3&roster_id=100011365&course_name=Test%20Course%201.2&mode=browse&course_number=0000&mode_id=1";
char strTemp[1024];
char *s = (char*)strBuffer;
int i=0;
while (*s)
{
strTemp[i++] = *s;
if (strncmp(s,"&",5) == 0)
{
s += 5;
}
else
s++;
}
strTemp[i] = 0;
未来的修改:
- 创建一个实用函数来存储这个函数.
- 将搜索字符串作为参数传递.
- 确定搜索字符串的长度,以便可以删除硬编码的 5.
- 动态分配 strTemp 变量.
- 未找到空字符串和字符的错误检查.
我创建了一篇博文来详细说明步骤并提供更灵活的解决方案:
I created a blog post to detail the steps and provide a more flexible solution:
http:///www.solutionmaniacs.com/blog/2012/11/25/c-removereplace-characters-in-a-string.html
推荐答案
char *s = (char*)strBuffer;
char sClean[strlen(strBuffer) + 1]; /* +1 for null-byte */
/* if above does not work in your compiler, use:
char *sClean = (char*)malloc(sizeof(strBuffer) + 1);
*/
int i=0;
while (*s)
{
sClean[i++]= *s;
if ((*s == '&') && (!strncmp(s, "&", 5)) s += 5;
else s++;
}
sClean[i] = 0;
这篇关于从 C 中的字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!