Created: 2023-01-15 17:57
Status: #concept
Subject: Programming
Tags: C C String Library Function stdio.h
string.h
Description
What does
strcpy
(String Copy) do? What's the syntax?
char *strcpy(char *str1, const char *str2);
- The
strcpy()
function copies the string pointed by sourcestr2
(including the null character) to the destinationstr1
. - Think of it as:
destination = source
orstr1 = str2
. - It returns the copied string.
strncpy(str1, str2, sizeof(str1));
- Copies
str2
tostr1
untilsizeof(str1)
. - Safer and guarantees no characters to overlap inaccessible Memory Addresses.
What does
strlen
(String Length) do? What’s the syntax?
size_t strlen(const char *str);
It returns the length of a string str
: up to, but not including the first '\0'
.
What does
strcat
(String Concatenation) do? What’s the syntax?
char *strcat(char *str1, const char *str2);
- Appends the Characters of the source string
str2
to the end of the destination stringstr1
starting from the Null Terminator\0
, then adds another\0
at the end. - Returns a Pointer to the resulting string str1.
char *strncat(char *str1, const char *str2, size_t n);
What does
strcmp
(String Comparison) do? What’s the syntax?
int strcmp(const char *str1, const char *str2);
- Compares
str1
andstr2
, returning a value less than, equal to, or greater than 0, depending on lexicographic ordering of the elements of str1 and str2.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[50] = "Hello", s2[50] = "Hello";
printf("%d", strcmp(s1, s2)); // outputs 0
char s1[50] = "Hello", s2[50] = "Hello World";
printf("%d", strcmp(s1, s2)); // outputs -1
char s1[50] = "Hello World", s2[50] = "Hello";
printf("%d", strcmp(s1, s2)); // outputs 1
}
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 13.5