#include <stdio.h>
#include <string.h>
int main(void) {
// Declare a string
char str[] = "Hello, world!";
// Find the length of the string
int len = strlen(str);
printf("Length of '%s': %d\n", str, len);
// Copy the string to a new buffer
char buffer[len + 1];
strcpy(buffer, str);
printf("Copied string: '%s'\n", buffer);
// Concatenate two strings
char s1[] = "Hello, ";
char s2[] = "world!";
strcat(s1, s2);
printf("Concatenated string: '%s'\n", s1);
// Compare two strings
char s3[] = "hello";
char s4[] = "world";
int result = strcmp(s3, s4);
if (result < 0) {
printf("'%s' comes before '%s' in the alphabet\n", s3, s4);
} else if (result > 0) {
printf("'%s' comes after '%s' in the alphabet\n", s3, s4);
} else {
printf("'%s' and '%s' are the same\n", s3, s4);
}
return 0;
}
When you compile and run this program, you should see the following output:
Length of 'Hello, world!': 13
Copied string: 'Hello, world!'
Concatenated string: 'Hello, world!'
'hello' comes before 'world' in the alphabet
This program demonstrates how to use the following string functions:
strlen
: Returns the length of a string (not including the null terminator).strcpy
: Copies the contents of a string into a destination buffer.strcat
: Concatenates (appends) one string to the end of another.strcmp
: Compares two strings lexicographically (alphabetically) and returns a value indicating their relative order.
0 Comments