I know this is a tad old, but I was trying the exercises (the first was very easy, not bothering to post here), and wanted to know if my solution for the second exercise contains any "bad practices" etc.
Make a program that concatenates 2 strings and shows the resulting string and its length.
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char* string1 = "Hello ";
char* string2 = "World";
int length = strlen(string1) + strlen(string2);
char* string3 = malloc(length);
strcpy(string3, string1);
strcat(string3, string2);
printf("%s\nLength = %d", string3, length);
return 0;
}
[/spoiler]
I intend to do the other exercises as well, and follow through any exercises in later parts of the tutorial as well, but I just wanted to check if I am making any big mistakes before moving on (of course, I have tested the program and it works fine, but that doesn't necessarily mean it is well coded).
EDIT: Some more solutions:
Make a program that shows the average length of 4 strings.
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* string0 = "This is the first string";
char* string1 = "This is the second string";
char* string2 = "This is the third string";
char* string3 = "This is the fourth string";
double average = (double) strlen(string0) + (double) strlen(string1) + (double) strlen(string2) + (double) strlen(string3);
average /= 4.0;
printf("Average length = %g", average);
return 0;
}
[/spoiler]
Make a program that having the string "Hello dang world", manipulates it and prints "Hello world".
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* string0 = "Hello dang world";
char string1[20];
memset(string1, 0, 20);
strncpy(string1, string0, 6);
strcat(string1, "world");
printf("Final string = %s", string1);
return 0;
}
[/spoiler]
Make a program that erases everything on a string after the string "me" (this one included).
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* string0 = "This string has me in it";
int length = strlen(string0) - strlen(strstr(string0, "me")) + 2; //+2 to include "me"
char* string2 = malloc(length);
strncpy(string2, string0, length);
printf("Original String = %s\nNew String = %s", string0, string2);
return 0;
}
[/spoiler]
This doesn't give quite the expected output. There are random characters appended to the output of "string2"; obviously some error in allocating memory or something, but I can't figure out what's wrong. I have allocated string2 "length" bytes of memory, then copied "length" bytes into it; why is it not working right?