Skip to content

Instantly share code, notes, and snippets.

@avoidedlife
Forked from sirovenmitts/string_joiner.c
Created February 15, 2013 21:44
Show Gist options
  • Save avoidedlife/4963791 to your computer and use it in GitHub Desktop.
Save avoidedlife/4963791 to your computer and use it in GitHub Desktop.
// ask for two strings and join the first half of the first string
// with the second half of the second string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 255
bool getInput( char *aString ) {
printf( "Please enter a long string: " );
if( fgets( aString, SIZE, stdin ) == aString ) {
int lastElement = strlen( aString ) - 1;
if( aString[ lastElement ] == '\n' || aString[ lastElement ] == '\r' ) {
aString[ lastElement ] = '\0';
}
return true;
}
return false;
}
void printStringSize( char *aString ) {
printf( "The string \"%s\" is %zu bytes long\n", aString, strlen( aString ) );
}
int main( void ) {
char
firstString[ SIZE ],
secondString[ SIZE ],
thirdString[ SIZE ];
if( getInput( firstString ) ) {
if( getInput( secondString ) ) {
printStringSize( firstString );
printStringSize( secondString );
int firstStringHalfwidth = strlen( firstString ) / 2;
int secondStringHalfwidth = strlen( secondString ) / 2;
int lastHalfOfSecondString = strlen( secondString ) - secondStringHalfwidth;
strncpy( thirdString, firstString, firstStringHalfwidth );
strncpy(
&thirdString[ firstStringHalfwidth ],
&secondString[ secondStringHalfwidth ],
lastHalfOfSecondString );
printf( "%s\n", thirdString );
return 0;
}
}
err( 1, "For some reason I was unable to get input from you. Oh well.\n" );
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment