Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Goutam Majumder
1 Introduction
2 Input a String
3 Issues Related to scanf()
4 puts() vs printf()
5 String Library Functions
6 strlen() vs sizeof() in C
7 Palindrome Problem
8 Some String Programs
9 Extra Out of Box
Declaration a String
Declaring a string is as simple as declaring a one dimensional (1-d) character
array. Below is the basic syntax for declaring a string.
In the above syntax str name is any name given to the string variable and
size is used define the length of the string, i.e the number of characters
strings will store. Please keep in mind that there is an extra terminating
character which is the null character (‘\0’) used to indicate termination of
string.
Goutam Majumder (LPU) Strings in C October 22, 2018 3 / 17
Introduction to String in C
Initializing a String
A string can be initialized in different ways. We will explain this with the
help of an example. Below is an example to declare a string with name as
str and initialize it with “Lovely”.
We can see in the above program that strings can be printed using a normal
printf statements just like we print any other variable. Unlike arrays we do
not need to print a string, character by character. The C language does not
provide an inbuilt data type for strings but it has an access specifier “%s”
which can be used to directly print and read strings.
scanf(“%s”,str);
scanf(“%[ˆ\n]%*c”,str);
puts(str); printf(“%s”,str);
If you do not want the cursor to be moved to next line, then you can
use following variation of puts().
fputs(str,stdout);
sizeof()
sizeof operator is a compile time unary operator which can be used to com-
pute the size of its operand.
– The result of sizeof is of unsigned integral type which is usually denoted
by size t.
– sizeof can be applied to any data-type, including primitive types such as
integer and float, or compound datatypes such as structure, union etc.
strlen()
strlen() is a predefined function whose definition is contained in “string.h”.
– strlen() accepts a pointer to an array as argument and walks through
memory from the address and looking for a NULL character and counts up
how many memory locations it passed before it finds one.
– The main task of strlen() is to count the length of an array or string.