Topic: | Strings (C) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 14, 2009 |
Array of char terminated by '\0' (NULL).
char s[MAX_STRLEN];
char *sptr;
sptr = malloc(sizeof(char) * MAX_STRLEN);
size_t strlen(const char *s) {
size_t i;
for (i = 0; s[i] != 0; i++) ;
return (i);
}
if (strcmp(s1, s2) == 0)
printf("%s is the same as %s\n", s1, s2);
char *strrchr(const char *s, int c) {
char *sp;
for (sp = s[strlen(s) - 1]; sp != s; sp--)
if (*sp == c)
return (sp);
return (NULL);
}
char *strcpy(char *dst, const char *src) {
char *dp, *sp;
dp = dst;
sp = src;
while (*sp != 0)
*dp++ = *sp++;
return (dst);
}
char s[MAX_STRLEN];
strcpy(s, "Hello, ");
strcat(s, "World!");
char *s = "words separated by spaces.";
char *d = " ";
char *sp;
sp = strtok(s, d);
while (sp) {
puts(sp);
sp = strtok(NULL, d);
}
#include <string.h> // C
#include <cstring> // C++
Some functions include a n variant where you can specify the length of strings; this can be more efficient, and usually safer.
Check man pages for more information:
$ man string $ man strlen