• A string is a array of characters.
• A string can also be defined as sequence of zero or more characters followed by a
NULL character(\0).
Examples:
“HELLO WORLD”
“WELL DONE”
The memory representation of the above can be given as:
Declaration of a string
• There is no separate data type for strings in C.
• They are treated as array of characters.
• They can be declared as:
char s[5];
This string can hold 5 characters including NULL character.
This can be represented as:
s[0] s[1] s[2] s[3] s[4]
Initialization of Array:
char s[5]={‘r’, ‘a’, ‘m’, ‘a’};
Dr. Vinod Desai, Dept. of CSE, SVIT Page 1
char s[5]=“rama”;
Reading and Printing string:
The strings can be read from keyboard and can be displayed in 2 ways.
puts(output)
Reading Strings
o If we declare a string by writing
char str[100];
o We can read the string ‘str’ by using 3 ways, namely:
1. using scanf() function
2. using gets() function
3. using getchar(), getch() and getche() function repeatedly
1. Using scanf() function:
We can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters the first
whitespace character(space, newline, tab, etc.).
It terminates reading further and appends a null character to the string that has
been read
Syntax:
scanf(“%s”,str);
Example: C program to scan a string variable using scanf()
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
Dr. Vinod Desai, Dept. of CSE, SVIT Page 2
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
OUTPUT:
Enter name: Dennis Ritchie
Your name is Dennis
Even though Dennis Ritchie was entered in the above program, only "Dennis" was
stored in the name string. It's because there was a space after Dennis.
Also notice that we have used the code name instead of &name with scanf().
This is because name is a char array, and we know that array names decay to
pointers in C.
Thus, the name in scanf() already points to the address of the first element in the
string, which is why we don't need to use &.
2. Using gets() function:
Reads characters from the standard input (stdin) and stores them as a C string
into the string variable ‘str’ until a newline character or the end-of-file is reached.
All the characters entered by the user get stored in a character array. The null
character is added to the array to make it a string.
The gets() allows the user to enter the space-separated strings. It returns the
string entered by the user.
It is not safe to use because it does not check the array bound.
It is used to read strings from the user until a newline character is not
encountered.
Example:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string:\n ");
gets(s);
printf("You entered: \n%s",s);
}
Output:
Enter the string:
Programming is the best
Dr. Vinod Desai, Dept. of CSE, SVIT Page 3
You entered:
Programming is the best
Difference between scanf() and gets() :
scanf() gets()
when scanf() is used to when gets() is used to read input it
read string input it stops stops reading input when it
reading when it encounters encounters newline or End Of File. It
whitespace, newline or End does not stop reading the input on
Of File encountering whitespace as it
considers whitespace as a string.
It is used to read input of It is used only for string input.
any datatype
Its syntax is -: Its syntax is -:
scanf(const char *format, char *gets(char *str)
…)
It is fast to take input. It takes one parameter that is the
pointer to an array of chars
Format specifiers is used Its return value is str on success else
inside scanf to take input. NULL.
3. Using getchar() function:
C getchar is a standard library function that takes a single input character from
standard input
It is defined inside the <stdio.h> header file.
Syntax of getchar() in C
getchar(void);
getchar() function does not take any parameters.
Return Value
The input from the standard input is read as an unsigned char and then it is
typecast and returned as an integer value(int).
EOF is returned in two cases:
o When the file end is reached
o When there is an error during the execution
Example:
int main()
{
char character;
Dr. Vinod Desai, Dept. of CSE, SVIT Page 4
printf(“Enter the character\n”);
character = getchar();
printf("The entered character is :\n %c", character);
return 0;
}
Output:
Enter the character
g
The entered character is :
g
Writing Strings
Strings can be displayed on monitor screen using three ways:
1. Using printf() function
2. Using puts() function
3. Using putchar() function repeatedly
1. Using printf() function
We can use the printf() function to display/print a string to the monitor screen.
The printf() function prints the string from first character to the last character
until it encounters a null character.
Syntax:
printf(“%s”,str);
Example: C program to scan a string variable using scanf()
#include <stdio.h>
int main()
{
char name[20] = “Programming is Fun”;
printf("String content is \n%s.", name);
return 0;
}
Output:
String content is
Programming is Fun
The conversion character ‘s’ is used to print the string in the format specifier “%s”
Dr. Vinod Desai, Dept. of CSE, SVIT Page 5
The width and precision specifications also could be used along with format
specifier
o The width specifies the total number of characters to be displayed. If the string is
short, extra space is left padded or right padded
o A negative width justifies the string to the left rather its usual right justification
o The Precision specifies the maximum number of characters to be displayed.
o If the string is long, the extra characters are truncated
o If the field width is less than the length of the string, the entire string will be
printed
o If the precision is zero, then nothing is printed on the string
Example
#include <stdio.h>
int main()
{
char str[10] = "COMPUTER";
printf("|%s|\n",str);
printf("|%20s|\n",str);
printf("|%20.4s|\n",str);
printf("|%-20.4s|\n",str);
printf("|%5s|\n",str);
printf("|%20.0s|\n",str);
printf("|%*.*s|\n",10,5,str);
}
Output:
|COMPUTER|
| COMPUTER|
| COMP|
|COMP |
|COMPUTER|
| |
| COMPU|
2. Using puts() function
puts() is a function defined in header <stdio.h> that prints strings character by
character until the NULL character is encountered
The puts() function prints the newline character at the end of the output string.
Syntax
puts(str);
where, str: string to be printed.
Dr. Vinod Desai, Dept. of CSE, SVIT Page 6
Return Value
The return value of the puts function depends on the success/failure of its execution.
o On success, the puts() function returns a non-negative value.
o Otherwise, an End-Of-File (EOF) error is returned.
Example:
#include <stdio.h>
int main()
{
// using puts to print hello world
char str = "Programming in C";
puts(str);
puts("Programming is Fun");
return 0;
}
Output:
Programming in C
Programming is Fun
3. Using putchar() function
The putchar(int ch) method in C is used to write a character, of unsigned char
type, to monitor screen. This character is passed as the parameter to this method.
Syntax:
putchar(ch);
Parameters:
This method accepts a mandatory parameter ch which is the character to be written
to stdout.
Return Value:
This function returns the character written on the screen as an unsigned char. It also
returns EOF when some error occurs.
Since the putchar() is capable of printing only one character to the screen, the
function needs to be repeatedly called to print the entire string.
Example:
#include <stdio.h>
int main()
{
// using putchar to print Computer Device
char str = "Computer Device";
int i=0;
Dr. Vinod Desai, Dept. of CSE, SVIT Page 7
while(str[i]!=’\0’)
{
putchar(str[i]);
i++;
}
return 0;
}
Output:
Computer Device
Suppressing Input
The scanf() is used to read a data without assigning it to any variable.
This is done by preceeding that field’s format code with a ‘*’
The * is a suppressing character which tells scanf to consume the input but not
try to assign it to a variable and the c conversion specifier asks to read any character
Example:
#include <stdio.h>
int main()
{
scanf(“%d*c%d”,&hr,&min);
scanf("%s %*c %s",s1,s2);
printf("%s %s\n",s1,s2);
scanf("%d %*c %d",&hr,&min);
printf("%d %d\n",hr,min);
}
Output:
Hello - Everyone
Hello Everyone
10 : 45
10 45
The string can be read as Hello - Everyone, here ‘-‘ the, would be read but not
assigned to anything
Thus, assignment suppression is helpful when part of what input needs to be
suppressed
Dr. Vinod Desai, Dept. of CSE, SVIT Page 8
Using a Scanset
scanf family functions support scanset specifiers which are represented by %[].
Inside scanset, we can specify single character or range of characters. While
processing scanset, scanf will process only those characters which are part of scanset
We can define scanset by putting characters inside square brackets. Please note
that the scansets are case-sensitive.
Example:
scanf(%[A-Z_abc]s,str);
This will scan all the specified character in the scanset i.e., All capital letters, an
underscore and only lowercase a,b,c alphabets and stops reading the string on
encountering the first non scanset character from keyboard
If first character of scanset is ‘^’, then the specifier will stop reading after first
occurrence of that character. For example, given below scanset will read all
characters but stops after first occurrence of the character ‘9’
Example
scanf(%[^9]s,str);
C program to demonstrate scanset in scanf() function
#include <stdio.h>
int main(void)
{
char str[128],str2[20];
printf("Enter a string with : ");
scanf("%[ A-za-z0-9!@#]s", str1);
printf("You entered: %s\n", str);
printf("You entered: %s\n", str1);
printf("Enter a string without vowels: ");
scanf("%[^aeiou]s", str2);
printf("You entered: %s\n", str);
return 0;
}
Output:
Enter a string : Hello Everyone 123@#$%^&*ju
You entered: Hello Everyone 123@#
Enter a string without vowels : qwerty keyboard
You entered: qw
Dr. Vinod Desai, Dept. of CSE, SVIT Page 9
sprintf and sscanf:
sprintf: It stands for "string print formatted." It is used to write formatted data to a
string.
Example:
#include <stdio.h>
int main() {
char buffer[50];
int num = 42;
float fnum = 3.14;
// Format the data into a string
sprintf(buffer, "The number is %d and the float is %.2f", num, fnum);
// Print the formatted string
printf("%s\n", buffer);
return 0;
sscanf: It stands for "string scan formatted." It is used to read data from a string into
variables, using a format specifier.
#include <stdio.h>
int main() {
char data[] = "The number is 42 and the float is 3.14";
int num;
float fnum;
// Extract data from the string
sscanf(data, "The number is %d and the float is %f", &num, &fnum);
// Print the extracted values
Dr. Vinod Desai, Dept. of CSE, SVIT Page 10
printf("Extracted values: %d, %.2f\n", num, fnum);
return 0;
In this example, reads the values of and from the string using
the specified format, and then we print the extracted values.
In this example, formats the integer and float into the string
buffer, and then we print the contents of which will be "The number is 42 and
the float is 3.14".
Dr. Vinod Desai, Dept. of CSE, SVIT Page 11
*****End*****
Dr. Vinod Desai, Dept. of CSE, SVIT Page 12