从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";
我需要修改此缓冲区以替换所有& amp; / code>与
&
。生成的缓冲区不必重写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函数,但是正在寻找一个更简单的解决方案,到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.
编辑:
,以下是我需要的。
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;
未来的修改:
- 创建一个效用函数来存储此函数。
- 将搜索字符串作为参数传递
- 确定搜索字符串的长度,
- 错误检查未找到空字符串和字符。 $ b $ b
- Create a utility function to store this function.
- Pass the search string as a parameter.
- Determine the search string's length, so the hardcoded 5's can be removed.
- Dynamically allocate the strTemp variable.
- Error checking for empty strings and chars not found.
EDIT:
我创建了一篇博文步骤并提供更灵活的解决方案:
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 < a>
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屋!