HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Primitive String trimmer in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stringtrimmerprimitive

Problem

I just picked up C and am following through The C programming language.

I've previously got experience with a lot of 'higher'-level languages, so when I saw this exercise in the book:


Write a program to copy its input to its output, replacing each string of one or more blanks by a
single blank.

I thought I'd create a very basic and primitive trim-program that takes an input and removes all superfluous white-spaces (more than 1 in a row) and prints out a 'trimmed' string.

As mentioned I just recently started and we haven't covered dynamic arrays yet, so I'm just using static ones.

But I was hoping to get some feedback on my solution:

#include 

/*
** A primitive trimmer
** to remove any superflous
** whitespaces in a given
** string (input).
*/

int main () {

    /*
    ** Setting up the variables
    **
    ** Working with static
    ** arrays since I haven't
    ** been introduced to dynamic.
    */
    char input [100], output[100];
    fgets(input, 100, stdin);
    int i = 0, k = 0;

    // Looping over input until hitting
    // an item containing a null-char.
    while (input[i] != '\0') {
        if (input[i] == ' ') { // hitting first space.
            int j = i + 1;     // initiating temporary counter.
            if (input[j] != '\0') {
                               // find index of first non-space
                               // character after initial space.
                while (input[j] != '\0' && input[j] == ' ') {
                    if (input[j] == ' ') {
                        i++; // keep indexing input-index
                    }
                    j++; // keep incrementing temporary indexer.
                }
            }
        }
        output[k] = input[i]; // insert non-space item into output.
        i++;                 // increment input-indexer.
        k++;                 // prepare output-indexer for next non-space.
    }
    printf("%s", output);     // print trimmed input.
}


It's not going to be prett

Solution

int vs size_t

Accordingly to the c language specification, it's highly recommendable to use size_t as the type for index variables. So in your case...

int i = 0, k = 0;


should be:

size_t i = 0, k = 0;


if condition repeats while condition

I was a bit confused by this piece of code

while (input[j] != '\0' && input[j] == ' ') {
  if (input[j] == ' ') {
    i++; // keep indexing input-index
  } 
  j++; // keep incrementing temporary indexer.
}


Specifically the if condition - it will always be true due to the while condition logic. So, as result, variable j just duplicates i with an invariant j = i+1.

Lack of null character

If you test your code on any string input, you will notice that the program prints some strange characters after your result. It happens because you didn't copy the \0 character to the output array.

Taking all this into an account (as well as @pacmaninbw's and @holroy's recommendations)

#include 
#include 

#define MAX 100

int
main ()
{
  char input [MAX], output[MAX];
  fgets(input, MAX, stdin);
  size_t inputIndex = 0, outputIndex = 0;

  while (input[inputIndex] != '\0')
    {   
      output[outputIndex++] = input[inputIndex];
      if (input[inputIndex] == ' ')
        while(input[++inputIndex] == ' ')
          ;   
      else
        inputIndex++;
    }   
    output[outputIndex] = '\0';
    printf("%s", output);
}

Code Snippets

int i = 0, k = 0;
size_t i = 0, k = 0;
while (input[j] != '\0' && input[j] == ' ') {
  if (input[j] == ' ') {
    i++; // keep indexing input-index
  } 
  j++; // keep incrementing temporary indexer.
}
#include <stdio.h>
#include <ctype.h>

#define MAX 100

int
main ()
{
  char input [MAX], output[MAX];
  fgets(input, MAX, stdin);
  size_t inputIndex = 0, outputIndex = 0;

  while (input[inputIndex] != '\0')
    {   
      output[outputIndex++] = input[inputIndex];
      if (input[inputIndex] == ' ')
        while(input[++inputIndex] == ' ')
          ;   
      else
        inputIndex++;
    }   
    output[outputIndex] = '\0';
    printf("%s", output);
}

Context

StackExchange Code Review Q#161401, answer score: 9

Revisions (0)

No revisions yet.