JC said:
sorry . i got one more problem
i got a string with 4 char. i want to put that in a string with 26 char. how
can i fill space on the remain char.. ??
is that i need to do a while loop do fill the space for the string?
No need to double-post, I was already at it
!
ANTI-SPOIL-DISCLAIMER: If this is homework, stop reading RIGHT NOW! ;-)
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
The following should work (any corrections/suggestions are welcome).
[Note: for pre-C99 drop the restrict keyword]
/*------------------8<----------------*/
#include <stdio.h>
#include <stdlib.h>
/*
** Prototype:
*/
char *Strncpypad( char * restrict s1, const char * restrict s2,
size_t n, int pad_char );
/*
** Simple test:
*/
#define BUFLEN 27
int main( void )
{
char s[ BUFLEN ] = "This is a garbage string!!";
char t[] = "abcd";
printf( "s before: '%s'\n", s );
printf( "t before: '%s'\n", t );
Strncpypad( s, t, BUFLEN, ' ' );
printf( "s after : '%s'\n", s );
return EXIT_SUCCESS;
}
/*
** Strncpypad
**
** Copy up to n-1 characters from the string pointed to by s2 to the
** array pointed to by s1. Characters that follow a null character
** are not copied. The result will be padded with pad_char, if
** applicable, and will always be null-terminated.
*/
char *Strncpypad( char * restrict s1, const char * restrict s2,
size_t buflen, int pad_char )
{
size_t i;
for ( i = 0; i < buflen-1; i++ )
{
if ( *s2 )
s1[ i ] = *s2++;
else
s1[ i ] = pad_char;
}
s1[ i ] = '\0';
return s1;
}
/*------------------8<----------------*/
Regards
Irrwahn