Skip to content

Instantly share code, notes, and snippets.

@draganmarjanovic
Created July 24, 2016 09:11
Show Gist options
  • Save draganmarjanovic/c2d1d8a53725dab47ec7b06107ec58b3 to your computer and use it in GitHub Desktop.
Save draganmarjanovic/c2d1d8a53725dab47ec7b06107ec58b3 to your computer and use it in GitHub Desktop.
C String Exercises
//Ex.4 - Write a function that reads a line of any length from a file and
//returns it as a string.
#include <stdio.h>
#include <stdlib.h>
/*
* Counts the length of NUL terminated
* character array.
*/
int dstrlen(char *string){
int count = 0;
while(string[count]) {
count++;
}
return count;
}
char* dstrcpy(char *dst, const char *src){
int count = 0;
while (src[count]){
dst[count] = src[count];
count++;
}
dst[count] = src[count];
return dst;
}
char* dstrcat(char *dst, char *src){
int concat_index = dstrlen(dst);
dstrcpy(&dst[concat_index], src);
return dst;
}
/*
*/
char* stringadd(char *a, char *b){
int new_length = (dstrlen(a) + dstrlen(b) + 1);
char *new_string = malloc(sizeof(char) * new_length);
dstrcpy(new_string, a);
dstrcat(new_string, b);
return new_string;
}
int main(int argc, char **argv) {
char first[] = "dragan";
char last[] = "marjanovic";
char *new_string;
printf("First: %s, Last: %s, New:%s\n",first,last,new_string);
new_string = stringadd(first, last);
printf("First: %s, Last: %s, New:%s\n",first,last,new_string);
free(new_string);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment