0

Looking for a more efficient way to replace leading and trailing empty spaces (' ') and appending an 'X' to the front for each empty space.. It seems to work ok for trailing spaces but I'd like to know if there's a better / simpler way of going about this that I am missing.

Example:

Passed in string: '12345 ' Desired result 'XXXXX12345'

Removed 5 empty spaces and append 5 'X's to front.

Example:

Passed in string: ' 12345' Desired result 'XX12345'

Remove 2 empty spaces and append 2 'X's to front.

void fixStr(char* str)
{
    int i = 0;
    int length = strlen(str);
    char strCopy[10];
    strcpy(strCpy, str);

    for(i = 0; i < length; i++)
    {
        if(strCopy[i] == ' ')
        {
            strCopy[i] = '\0';
            str[i] = '\0';

            break;
        }
    }
    for(i = 0; i < length - i + 2; i++)
    {
        str[i] = 'X';
        str[i + 1] = '\0';
    }
    strcat(str, strCopy);

}

5
  • 1
    Passed in string: '12345 ' Desired result 'xxxxx12345' - what exactly is the logic here??? Commented Dec 22, 2020 at 6:52
  • 1
    And BTW, s_length is used but not declared and initialized anywhere in your code! Commented Dec 22, 2020 at 6:54
  • Note that strCopy should be sized char strCopy[length + 1] for anything like safety. Commented Dec 22, 2020 at 6:54
  • You talk about X and your examples used x instead; I've converted the examples to use upper-case, but you should really be self-consistent in your question. Attention to that sort of detail is a prerequisite for successful programming. Commented Dec 22, 2020 at 6:58
  • Passed in string: '12345 ' Desired result 'XXXXX12345' there are no leading spaces here only trailing spaces, why are you adding XXXXX to the string? Commented Dec 22, 2020 at 8:01

3 Answers 3

1

One way to achieve this is to find out the leading non-space position & trailing non-space position of the string, and then move the content in-between (leading nonspace, trailing nonspace) this to end of the string, then set all the empty space at the beginning to 'x'

This way you can get the expected output (function below)

void fixStr(char* str)
{
    int i = 0;
    int length = strlen(str);
    int leadindex = length; 
    int tailindex = 0;
    // First find the leading nonspace position
    for(i = 0; i < length; i++)
    {
        if(str[i] != ' ')
        {
            leadindex = i;
            break;
        }
    }
    
    // if not found nonspace then no change
    if( leadindex == length ) 
    {
        // all spaces, so no change required;
        return;
    }
    
    // Find the trailing nonspace position 
    for(i = length - 1; i >= 0 ; i--)
    {
        if(str[i] != ' ')
        {
            tailindex = i;
            break;
        }
    }
    
    // move the buffer (in place) to exclude trailing spaces
    memmove(str + (length - tailindex -1),str,(tailindex +1) );
    // set the 'x' to all empty spaces at leading ( you may use for loop to set this)
    memset(str, 'X', length - (tailindex - leadindex + 1) );

}
Sign up to request clarification or add additional context in comments.

Comments

1

To solve a problem the engineer's way:

  1. Define the needs.
  2. Know your tools.
  3. Use the tools as simple as possible, as accurate as necessary to make up a solution.

In your case:

  1. Needs:

    • find the number of trailing spaces
    • move content of string to the end
    • set beginning to 'X's
  2. Tools:

    • to measure, iterate, compare and count
    • to move a block of memory
    • to initialise a block of memory
  3. Example for a solution:

    #include <string.h> /* for strlen(), memmove () and memset() */
    
    void fix_str(char * s)
    {
      if ((NULL != s) && ('\0' != *s)) /* Ignore NULL and empty string! */
      {
        /* Store length and initialise counter: */
        size_t l = strlen(s), i = l;
    
        /* Count space(s): */
        for (; (0 != i) && (' ' == s[i-1]); --i); /* This for loop does not need a "body". */
    
        /* Calculate the complement: */
        size_t c = l - i;
    
        /* Move content to the end overwriting any trailing space(s) counted before hand: */
        memmove(s+c, s, i); /* Note that using memmove() instead of memmcpy() is essential 
                               here as the source and destination memory overlap! */ 
    
        /* Initialise the new "free" characters at the beginning to 'X's:*/
        memset(s, 'X', c);
      }
    }
    

Comments

0

I didn't fix your code but you could use sprintf in combination with isspace, something along the lines of this. Also, remember to make a space for the '\0 at the end of your string. Use this idea and it should help you:

#include <ctype.h>
#include <stdio.h>

int main()
{
    char buf[11];
    char *s = "Hello";
    int i;
    
    sprintf(buf, "%10s", s); /* right justifies in a column of 10 in buf */
    
    for(i = 0; i < 10; i++) {
        if(isspace(buf[i])) /* replace the spaces with an x (or whatever) */
            buf[i] = 'x';
    }
    
    printf("%s\n", buf);
    
    return 0;
}

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.