Strings in C Language
Strings in C Language
1. Concepts of strings
2. String pointers
3. String operations
4. String library functions
1. Concepts of Strings
• Concepts of strings in C
1. A string is a sequence of characters terminated with the null
character stored in a char array.
2. Char array is used to hold a string. Each character is stored
in an array position one after another. The end of string is
marked by the null character ‘\0’
Note: the ASCII value of ‘\0’ is 0. NULL as pointer value of 0.
3. The length of a string is the number of non-null characters
in the string.
• Assign values ‘c’, ‘p’, ‘2’, ‘6’, ‘4’, ‘\0’ to the char array elements.
p is char type pointer and char type has 1 byte, p+1 increase the
value of p by 1.
String pointer
char *p = "cp264";
printf("%s\n", p); // output: cp264
printf("%c\n", *(p+2)); // output: 2
char *sp[2];
char *s0 = "cp264“;
char *s1 = “data structures II“;
sp[0] = s0;
sp[1] = s1;
Command:
a.out argument1 argument2
argc will have value 3
argv[0] points to string “a.out”
argv[1] points to string “argument1”
argv[2] points to string “argument2”
3. String operations
1. Read string from stdin
2. Write string to stdout
3. Length of a string
4. Change case
5. Copy string
6. Concatenate string
7. Compare string
8. Reverse string
General algorithm of string processing
Input: string str[] or char *str
Step 1: Set char *ptr = str
Step 2:
while (*ptr) { // traversal / scan the string by loop
If pattern is matched
take action
ptr++;
}
Step 3: stop
char str[100];
char name[20];
scanf(“%s”, name);
cp264 2024<enter>
printf(“%s”, name); // output: cp264
Output string to stdout (screen)
• stdio has three functions for stdout (screen) output
Example
char str[] = “data structures”;
char *p=str;
while(*p) putchar(*p++);
puts(str);
printf(“%s”, str);
Compute the length of a string
• The length of a string is the number of non-null characters.
Example
char *delim = “,. “; // comma, period, space as delimiters
char str[30] = “cp264, data structures.“;
char *token = strtok(str, delim); // get the first word
printf(“%s”, token); // output cp264
token = strtok(NULL, delim); // get the next word
printf(“%s”, token); // output data
token = strtok(NULL, delim); // get the next word
printf(“%s”, token); // output structures