Ics 2102 Strings
Ics 2102 Strings
TO COMPUTER
PROGRAMMING.
C STRINGS.
Since strings are actually arrays, you can access a string by referring to its index number inside square
brackets[].
To change the value of a specific character in a string, refer to the index number, and use single quotes.
You can also loop through the characters of a string, using a for loop:
char carName[]= “volvo”;
int i;
for(i=0,i<5;i++){
printf(“%c\n”, carName[i]);
}
Let’s use the sizeof() formula instead of manually writing the size of an array in the loop condition (i < 5)
to make the loop more ideal;
char carName[]= “volvo”;
int length = sizeof(carName)/sizeof([0]);
int i;
for(i=0,i< length;i++){
printf(“%c\n”, carName[i]);
}
Another way of creating strings.
So far we have used a ‘string lateral’ to create a string variable, which is the easiest way to create a string in C.
You can also create a string with a set of characters.
Example:
Char greetings[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’ ‘\o’};
Printf(“%s”, greetings);
Note: we include \o character at the end.
This is the null terminating character. It tells C that this is the end of the string.
C SPECIAL CHARACTERS.
When we want to use special characters like single quotes, double quotes and backslash within strings we use the
backslash escape character(\).
Example:
Char txt[]= “We are \”seniors\” here.”;
//outputs we are “seniors” here
Char txt[] = “It\’s okay”;
//outputs It’s okay
The backslash escape character turns special characters into string characters.
Other popular escape characters are;
\n – new line
\t – tab
\o – null
C STRING FUNCTIONS.
C also has many useful string functions, which can be used to perform certain operations on strings.
To use them, you must include the <string.h> header file in your program.
#include <string.h>
STRING LENGTH.
To get the length of a string, you can use the strlen( function):
Strcat(str1, str2);
//concatenate str2 to str1 result is stored in str1
Printf”%s”, str1);
Note: the size of str1 should be large enough to store the result of both strings combined.
COPY STRINGS
To copy the value of one string to another, you can use the strcpy() function.
Printf(“%s”, str2);
Note: the size of str2 should be large enough to store the copied string.
COMPARE STRINGS