Strings
Strings
1
Strings
Sequence of zero or more characters, terminated by NULL
‘/0’ (literally, the integer value 0)
NULl terminates a string
important for strlen() – length doesn’t include the NULL
Strings are accessed through pointers/array names
string.h contains prototypes of many useful functions
2
String literals
Evaluating ″dog″ results in memory allocated for three
characters ′d ′, ′ o ′, ′ g ′, plus terminating NULL
char *m = ″dog″;
Note: If m is an array name, subtle difference:
char m[10] = ″dog″;
3
String functions
C never lets us assign entire arrays, we use the strcpy function to copy one
string to another
source string write to destination location
strcpy(dst,src);
char string1[] = "Hello, world!";
char string2[20];
strcpy(string2, string1);
String2 = Hello, world!“
C program
strcpy(char dest[], char src[])
{ int i = 0;
while(src[i] != '\0')
{ dest[i] = src[i]; i++; }
dest[i] = '\0'; }
4
strlen() and size_t
size_t strlen(string s1);
/* returns length of string with out the null constant */
size_t is an unsigned integer type
int t =strlen(“india”); t=5
C program
strlen(s)
{
int i=0,len=0;
while( s[i]!=‘\0’)
i++;
len++;
}
5
strcmp() “string comparison”
int strcmp(s1,s2); Case discriminative
strcmp does not return a Boolean, true/false
Return zero/nonzero answer
returns a value less than zero if s1 precedes s2 in lexicographical order;
returns zero if s1 and s2 are equal;
returns a value greater than zero if s1 follows s2.
seems reasonable to assume that strcmp returns “true” (nonzero) if s1 and
s2 are equal; “false” (zero) otherwise
In fact, exactly the opposite is the case!
int stricmp(s1,s2); Non case senstive
strcmp(“hello”,”Hello”); output !=0
stricmp(“hello”,”Hello”); output =0
strncmp(s1,s2,n) compares only the two string upto specified length n
Strncmp(“Goodmorning”,”Goodday”,4) output -0
6
string functions strcat()
strcat() which concatenates strings.
It append one string onto the end of another.
NOT a new string third string
strcat(target,source) source string appened with target
strcat(“good”,”morning”); output =goodmorning
strncat(target,source,n)
7
strlwr () function strupr () function
NUL
line token