1

I am trying to copy from one string to another, but the second string should omit the space. I tried to approach this by saying, if a character in the original string is a space, do not copy it. Instead, copy the next character. However, the program deletes everything after the space. Any ideas?

char deleteSpaces(char phrase[256], int length){
int j, i=0;
char phrase2[length];
  for(j=0;j<length;j++){
    if(phrase[i]==' '){
        phrase2[j]=phrase[i+1];
        i++;
        }
    phrase2[j]=phrase[i];
  }

return phrase2;
}
4
  • 3
    Lots of undefined behavior in that code. Commented Mar 15, 2014 at 23:19
  • 3
    What if there are more than 2 spaces in sequence? Commented Mar 15, 2014 at 23:19
  • 3
    You're returning the address of a local variable, phrase2. Not good. You either need (1) pass in the address of the new array, (2) dynamically allocate a new address from the heap, or (3) modify the original string being passed in. Commented Mar 15, 2014 at 23:21
  • How about approaching this as just copy the character if it is not a space. As it is now you could run into a problem if your string ended with a space. Commented Mar 15, 2014 at 23:26

6 Answers 6

2

Here is a solution:

void deleteSpaces(char src[], char dst[]){
   // src is supposed to be zero ended
   // dst is supposed to be large enough to hold src
  int s, d=0;
  for (s=0; src[s] != 0; s++)
    if (src[s] != ' ') {
       dst[d] = src[s];
       d++;
    }
  dst[d] = 0;
}
Sign up to request clarification or add additional context in comments.

3 Comments

in the for-statement, is it s++ instead of src++?
@user3349993 This is the result the same for both.
@BLUEPIXY, user3349993: I was interrupted before rereading my code. fixed now.
2

First, you're returning a static tab and this is wrong. Secondly you don't increment 'i' if there is no space. And to finish you will copy spaces if there is more than one space in a row. And you do not control if you reach the end of your source.

for(j = 0; j < length; j++)
{
    while (src[i] == ' ' && i < length) i++;

    if (i < length)
        dest[j] = src[i++];
    else
    {
        dest[j] = 0;
        break;
    }
}

Comments

1

My solution. Arguments and their order are chosen to match strncpy().

#include <ctype.h>

char *strip_whitespace(char *dest, const char *src, size_t n)
{
    char *s, *d;

    /* 
     * Copy 'src' to 'dest', omitting whitespace and making sure we don't
     * overflow 'dest'.
     */
    for(s=src, d=dest; *s && (d-dest)<n; s++) {
        if( !isspace(*s) ) {
            *d = *s;
            d++;
        }
    }

    /* Ensure that dest is NUL terminated in any event */
    if( d-dest < n ) {
        *d = '\0';
    } else {
        dest[n-1] = '\0';
    }

    return dest;
}

Comments

1

As pointed out already you need to allocate a new string and return a pointer to it. This code works:

char* strip (char* input)
{
    int loop;
    char *output = (char*) malloc (strlen(input));
    char *dest = output;

    if (output)
    {
        for (loop=0; loop<strlen(input); loop++)
            if (input[loop] != ' ')
                *dest++ = input[loop];

        *dest = '\0';
    }
    return output;
}

int main (void)
{
    char srcString[] = "   this is a test with spaces   at     the end   ";
    char* dstString = strip (srcString);

    printf ("source string = '%s'\n", srcString);
    printf ("  dest string = '%s'\n", dstString ? dstString : "malloc failed in strip");

    free (dstString);

    return 0;
}

Output:

source string = '   this is a test with spaces   at     the end   '
  dest string = 'thisisatestwithspacesattheend'

It takes the input string and allocates a destination string the same size which is safe, although wasteful of a few bytes.

The method is simple; only copy a character if it is not a space. After all the characters are copied, I write the terminator on the end and return the pointer.

2 Comments

Some short-comings including off by 1, char *output = malloc(strlen(input) + 1);.
Indeed, in the specific case in which a string is passed to the function, which has absolutely no spaces
1

****WHAT YOU WERE DOING** IS THAT if a character in the original string is a space, do not copy it. Instead, copy the next character. IS NOT A GOOD idea because

Case 1. When multiple spaces are present, it simply discard the first spaces and copies the second one...

Case 2: Your programme copies the string only after space is found,,it is simply skipping the first word of string which doesn't start with spaces.

case 3. You are only returning the character pointed by phrase2[0] as return type is char,and the scope of local variable is limited to only that function....

//the corrected programme

int deleteSpaces(char phrase[256],charphrase2[256])
{
    int i,j;
    i=j=0;
    while(phrase[i]!=NULL){
        if(phrase[i]!=' '){
            phrase2[j]=phrase[i];
            j++;
         }
       i++;
     }//end while
     phrase2[j]=phrase[i] //nulcharceter copied

     return 0;
}//end deleteSpaces function

Comments

1

I use this:

 char input[100], foreval[100];
 for(i=0;i<strlen(input);i++){
    if(isspace(input[i])){
        continue;
    }
    strncat(foreval,&input[i],1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.