String
String
• C does not have a "string" datatype. To createa string you have to use a "char array" or a
"char pointer".
• Pointer we will learn later in this course.
• Strings are arrays of chars. String literals are
words surrounded by double quotation marks.
"This is a static string"
• To declare a string of 49 letters, you would
want to say: char string[50]; This would
declare a string with a length of 50 characters.
• a string ends with a null character, literally a
'\0' character
• It is not counted as a letter, but it still takes up
a space.
• A string constant is a one dimensional array of
characters. For example,
• Char name[]={'S','t','u','d','e',\0};
• This terminating null(\0) is important
because this is the way to know where string
ends.
• Another example of string,
• Main()
• {
Char name[]='Student';
while (name[i]!='\0)
{
printf("%c",name[i]);
i++;
}
}
• Output: Student
• The %s used in printf() is a format
specification for printing out a string.
• To receive a string a string same specification
can be used. For example,
• char name[10];
scanf("%s",name);
printf("%s",name);
As an example,
• char arr[6]="tanvir";
• Printf("%s",arr);
Output: tanvir
• When using scanf(), careful about two things
1. The length of string should not exceed the
dimension of character array.
2. scanf() is not capable of receiving multi-word
strings.
• So we can use gets() function to overcome
multi-word strings problem.
gets() and puts() are using for input and
output. As an example,
char name[10];
gets(name);
puts(name);
String Functions Library
• strlen finds length of a string• strlwr converts string to lowercase
• strupr converts string to uppercase
• strcat append one string at the end of another
string
• strcpy copies a string into another string
• strcmp compares two strings
• strncmp compares first n characters of two
strings
• strrev reverse string
• For example, the strlen(str) function returns
the number of characters in the string str.
• char a[l0],b[10];
• b = a;
does not appear to make a copy of the
characters in a.
To do this strcpy(a,b) which really does make a
copy of every character in a in the array b up
to the first null character.
• In a similar fashion strcat(a,b) adds the
characters in b to the end of the string stored
in a.
• Also, strcmp(a,b) which compares the two
strings character by character and returns true
- that is 0 - if the results are equal.
• < 0 if s1 is less than s2
• 0 if s1 == s2
• > 0 if s1 > s2
No comments