Insert Leading Spaces to String to Match Format

257 Views Asked by At

I have to create a string that has a fixed amount of chars. The format says that the string must be filled with leading spaces in case it isn't long enough.

How can I (elegantly) add these leading spaces?

P.S. I know I could count the length of the string and a space till I fill it but... I feel like there's gotta be a easier (more elegant) way of doing it. Perhaps with regular expressions?

2

There are 2 best solutions below

0
On BEST ANSWER

String.PadLeft Method (Int32, Char)

http://msdn.microsoft.com/en-us/library/92h5dc07.aspx

string str = "data";
char pad = ' ';

Console.WriteLine(str.PadLeft(10, pad));    // Displays "      data".
0
On

A little bit lower level, untested:

char *
padLeft ( char *s, size_t size ) {         // left-pad s to make a string of size chars
  char *d = malloc( size + 1 );
  if ( d != NULL ) {
    memset( d, ' ', size );
    strcpy( &d[size - strlen(s)] - 1, s ); // copy s (incl '\0'), filling the right part of d
  }
  return d;
}