Strings
- Strings are nothing but an array of characters - there is no primitive
stringtype in C. - Special null character
'\0'needed at the end of every string -
"string literal"is legal, compiler will make aconstarray of chars to hold it for you. - No string
+concatenation like in Java or Python -
#include <string.h>to access library functions; Reference forstring.hfunctions -
strlen(s)returns number of chars before'\0'
String library functions
- These functions show off pointers and
constwell - They use pointer types
char *for strings, not array typeschar [] - Memory must previously be allocated by you if you are passing a reference where the function will put a result.
- The functions use
constto indicate arguments they don't change
stdlib.h string conversion functions
-
double atof(const char *s) -
int atoi(const char *s) -
double strtod(const char *s, char **endp)
stdio.h string i/o functions
-
puts(s) -
gets(s)- very insecure, don't use - may overwrite memory not allocated to your program! -
fgets(s, MAXSIZE, stdin)- use this instead; must allocate memory for s first!
Common string.h string manipulation functions
-
strlen(const char *str)- length of string -
char *strcpy(char *dest, const char *orig) - copy from string
origto stringdest - return
dest -
strncpy(dest, orig, howmany)only copieshowmanycharacters -
char *strcat(char *orig, const char *more)- concatenate
moreto end oforig(orig = orig + more) - return
orig
- concatenate
-
int strcmp(const char *s1, const char *s2)- compare
s1tos2 - return
0if same,<0ifs1 < s2,>0ifs1 > s2
- compare
Dynamically allocating space for strings and putting them in an array:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void addstring(char **stringarray, char *newstring, int * numptr)
{ printf("allocating %lu bytes for %s\n",strlen(newstring)+1,newstring);
stringarray[*numptr] = malloc(strlen(newstring)+1);
strcpy(stringarray[(*numptr)++],newstring);
}
int main()
{
int numstrings = 0;
char *sarray[100];
addstring(sarray, "hi", &numstrings);
addstring(sarray, "ho", &numstrings);
addstring(sarray, "wee", &numstrings);
for (int i=0; i < numstrings; i++) {
printf("%s\n",sarray[i]);
// must also free the strings to prevent memory leaks
free(sarray[i]);
}
}
See also the Pointers & Dynamic Memory Allocation notes resource.