Possible Duplicate:
How do I replace multiple spaces with a single space in C?
I have a string in c that can contain two consecutive spaces. I want to remove two consecutive spaces with one space. How can I do that? Help please.
Possible Duplicate:
How do I replace multiple spaces with a single space in C?
I have a string in c that can contain two consecutive spaces. I want to remove two consecutive spaces with one space. How can I do that? Help please.
If it is the case that there is a single occurrence of two consecutive spaces in the string then a possibility would be to use strstr()
and memmove()
:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "a string with two spaces";
char* two_spaces_ptr = strstr(s, " ");
printf("[%s]\n", s);
if (two_spaces_ptr)
{
memmove(two_spaces_ptr + 1,
two_spaces_ptr + 2,
strlen(two_spaces_ptr + 2) + 1); /* +1 to copy the NULL. */
}
printf("[%s]\n", s);
return 0;
}
Output:
[a string with two spaces]
[a string with two spaces]
The C standard for memmove()
states:
The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1.
EDIT:
Updated answer to use memmove()
, instead of strcpy()
that resulted in undefined behaviour.
You can write over your own string:
char *ys = YOUR_STRING;
char *n = ys;
while (*ys)
{
*n = *ys;
if (*ys == ' ')
while (*ys == ' ')
ys++;
else
ys++;
n++;
}
Or you can create a new string:
char *ys = YOUR_STRING;
char *n = malloc(sizeof(*n) * strlen(ys));
int i = 0;
while (*ys)
{
n[i++] = *ys;
if (*ys == ' ')
while (*ys == ' ')
ys++;
else
ys++;
}
// use n
for (unsigned char *p = YOUR_STRING, *q = p; ((*q = *p));) {
if (*q++ == ' ') {
while (*++p == ' ');
} else {
p++;
}
}
Less obscure alternative:
unsigned char *p = YOUR_STRING;
unsigned char *q;
/* zap to the first occurrence */
while (*p && *p++ != ' ');
/* copy from here */
q = --p;
while ((*q = *p)) {
if (*q++ == ' ') {
while (*++p == ' ');
} else {
p++;
}
}
If you're sure there can be only two spaces consecutive at max, you can do something like:
int main ()
{
char *str="This is a wonderful world. Let's have a good time here.";
int len=strlen(str);
char *result = (char*)malloc(len);
int j=0;
for(int i=0;i<len;i++) {
if(str[i]==' ' && str[i-1]==' ') {
i++;
}
result[j++]=str[i];
}
result[j]='\0';
printf("%s\n", result);
return 0;
}