omega
omega

Reputation: 43843

How to trim a string of format char[]?

In my C program, I create a char array like char read_str[MAX_ALLOWED_BUFFER];. With this array, how can I trim the whitespace and newline characters from the left and right side of it. This isn't a pointer, so I don't understand how to get rid of the trailing characters. Can anyone help please?

char read_str[MAX_ALLOWED_BUFFER];
FILE *fp;
fp = fopen(argv[1],"r");
fgets(read_str, MAX_BUFFER, fp);
// how to trim read_str ?

Upvotes: 3

Views: 15322

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146073

One way would be to allocate a second string and process the first into the second...

#include <stdio.h>
#include <string.h>

#define MAX_ALLOWED_BUFFER 100

char read_str[MAX_ALLOWED_BUFFER] = "    a core string     ";
char result[MAX_ALLOWED_BUFFER];

int main(void) {
  char *t;

  read_str[MAX_ALLOWED_BUFFER - 1] = '\0'; // not needed here but wise in general
  // trim trailing space
  for(t = read_str + strlen(read_str); --t >= read_str; )
    if (*t == ' ')
      *t = '\0';
    else
      break;
  // trim leading space
  for(t = read_str; t < read_str + MAX_ALLOWED_BUFFER; ++t)
    if(*t != ' ')
      break;
  strcpy(result, t);
  printf("got <%s>\n", result);
  return 0;
}

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183888

To trim the white space from the end, just write a 0 in the appropriate place. The string handling functions interpret that as the end of the string. To remove the white space from the beginning, the easiest method is to use a pointer into the array and let that point to the first non-whitespace character. But you could also move the characters to the start of the array, e.g. with memmove.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

You need to identify the first non-whitespace character, and then copy the values from there to the start of the array. You then need to to identify the last non-whitespace character, and create a new null-terminator character after it.

Note that you're not actually deleting or removing anything, you're simply changing the values of characters in your array.

You may find some of the string-handling functions from the C standard library useful; here is a list of them: http://en.cppreference.com/w/c/string/byte.

Upvotes: 4

Related Questions