SE250:HTTB:Pointers:C Strings
<html>
<image src="http://www.rajithaonline.com/SE250/httb/pointers/final/strings_head.png" width="214" height="92" alt="Strings Header Logo" /> |
</html>
Previous Page | Contents | Next Page |
C Strings
The <string.h> library gives many useful functions for manipulating string data(copy strings and concatenating strings), comparing strings, searching strings for characters and other strings, tokenizing string and determining the length of strings.
The functions include:
char *strcpy(char *s1, char *s2) Copies string s2 into array s1. The value of s1 is returned. char *strncpy(char *s1, char * s2, int n) Copies at most n characters from s2 into s1. The value of s1 is returned. char *strcat(char *s1, char *s2) Appends string s2 to array s1. The first character of s2 overwrites the termination null character of s1. Value of s1 is returned char *strncat(char *s1, char *s2, int n) Appends at most n characters from s2 to s1. First character from s2 overwrites the terminating null character of s1. The value of s1 is returned.
String comparison methods:
int strcmp(char *s1, char *s2) Compares the string s1 with the string s2. The function returns 0, less than 0, or greater than 0 if s1 is equal to, less than or greater than s2. int strncmp(char *s1, char *s2, int n) Compares up to n characters of s1 with s2. Function returns 0, less than 0 or greater than 0 if s1 is equal to, less than or greater than s2.
String search methods:
char *strchr(char *s, char c) Find the first occurrence of character c in string s. Returns pointer to c in s if character is found. char *strpbrk(char *s1, char *s2) Locates the first occurrence of string s1 of any character in string s2. If a character from s2 is found, pointer to that character is returned. char *strrchr(char *s, char c) Locates the last occurrence of c in string s. If c is found, a pointer to c in string s is returned. char *strstr(char *s1, char *s2) Locates the first occurrence in string s1 of string s2. If string is found, then a pointer to the string in s1 is returned.
String Basics
A string is a series of characters treated as a single unit, and can contain letters, digits and various special characters. String literals, or string constants are written in double quotation marks for C.
String is an array of characters ending in the null character('\0'), and is accessed via a pointer to the first character in the string. Therefore, a string is a pointer to the string's first character.
Definitions:
char colour[]= "black"; char *colour = "orange";
String can be stored using the scanf function:
scanf("%s", word);
Note that word is an array which is a pointer storing the word entered by the user.
Previous Page | Contents | Next Page |