You are on page 1of 16

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 17: STRINGS IN C LANGAUGE


MCT-242L: Computer Programming-I Lab (Fall-2022)
Registration No. 2022_MC_33

OBJECTIVE:
This lab will introduce Strings in a C Language Program. At the end of this lab, you should be able to:

 Define, assign value, and access strings


 Read a line of text from user
 Use built-in string functions from string.h library
 Passing string as an argument of a function
 Define and use array of strings

APPARATUS:
 Laptop\PC with following tools installed
o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10

LAB SUBMISSION:
 Create a Visual Studio Code Workspace, Lab_17 and c files (Task_17_1.c to Task_17_6.c) for
individual tasks and add them to Lab_17 workspace.

STRINGS
Strings are one-dimensional array of characters terminated by a null character '\0'. Thus, a null-terminated
string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // simple string
Syntax to Declare a String of 5-Characters
If you follow the rule of array initialization, then you can write the above statement as follows:

char greeting[6] = "Hello"; // simple string


Another Way to Declare a String of 5-Characters
We must write greeting[6] (the last character is '\0') instead of greeting[5] to an array of 5 characters.
This is bad and we must never do it. The size of the array must be one more than the number of characters in
the string to allow for the null terminator.

1|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Following are the indices of the above defined string in C/C++:

Index 0 1 2 3 4 5
Variable 'H' 'e' 'l' 'l' 'o' '\0'

You do not place the null character at the end of a string constant. The C compiler automatically places the
'\0' at the end of the string when it initializes the array.

Assigning Values to Strings

Arrays and Strings do not support assignment operator once it is declared. For example

char greeting[6];
greeting = {'H', 'e', 'l', 'l', 'o', '\0'}; // Error! Array type is not assignable
Error while Assigning an Array after Declaration

Let us try to print the above-mentioned string:

Example 17.1: Strings in C


/* Example_17_1.c: Strings in C
----------------------------------------------------------------
This program demonstrates the idea of strings in C. As an example,
it shows how we can initialize and display array.
----------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 21-Nov-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
// initialize a simple string
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

// access the string elements


printf("Greeting message: %s\n", greeting);

return 0;
}

// End of program
Program Output Greeting message: Hello

2|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Read String from the User

We can use the scanf() function to read a string. The scanf() function reads the sequence of characters
until it encounters whitespace (space, newline, tab, etc.)

Example 17.2: Read String from User in C


/* Example_17_2.c: Read String from User in C
---------------------------------------------------------------
This program takes a string input from user.
---------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 22-Nov-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

// End of program
Enter name: Ali Khan
Program Output
Your name is Ali.

In above example, even though Ali Khan was entered, but only Ali was stored in the name string. It is
because of the blank space between Ali and Khan.

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 arrays names decay to pointers in C. Thus, the name in scanf() already points to
the address of first element in the string, which is why we don’t need to us &.

Read a Line of Text from the User

We can use the fgets() function to read a line of string. And we can use puts() to display the string.

Example 17.3: Read a Line of Text from User in C


/* Example_17_3.c: Read a Line of Text from User in C
---------------------------------------------------------------
This program takes a line of text input from user.
---------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 22-Nov-2021.
IDE: Visual Studio Code 1.60.0

3|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Your name is ");
puts(name); // display string
return 0;
}

// End of program
Enter name: Ali Khan
Program Output
Your name is Ali Khan

In Example 13.3, we have used fgets() function to read a string from the user. The sizeof(name) results
to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string. To print
the string, we have used puts(name). Though, fgets() and puts() handles strings, both these functions
are defined in stdio.h header file.

Example 17.4: Count a Letter from a Line of Text from User


/* Example_17_4.c: Count a Letter from a Line of Text from User
---------------------------------------------------------------
This program counts a specific letter appeared in a given line
of text input from user.
---------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 21-Nov-2022.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
char sentence[80], character;
int count = 0;

printf("Enter the text >> ");


fgets(sentence, sizeof(sentence), stdin); // read string

4|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

printf("Enter the character >> ");


scanf("%c", &character);

for (int i = 0; sentence[i] != '\0'; ++i)


{
if (character == sentence[i])
++count;
}

printf("Character \"%c\" appeared %d times.", character, count);

return 0;
}

// End of program

Enter the text >> This example program counts a specified


letter appeared in the given text line
Program Output
Enter the character >> e
Character "e" appeared 12 times.

TASK 17.1: Consonants, Vowels, & Digits [1 point]


Write a program that takes a string as an input from user and returns
the number of consonants, vowels, and digits in it.
Please enter a line of string >> Quick Brown Fox jumps
over the Lazy Dog
Sample Output
Number of Vowels in given string are 10
Number of Consonants in given string are 22
Number of Digits in given string are 0

5|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Answer:

TASK 17.2: Only Alphabets [1 point]


Write a program that takes a string of any character from the user and
display only the alphabets present in the entered string.
Please enter the string >> e’$’ng%in*e*e*r
Sample Output
Output string of alphabets = engineer

Answer:

6|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

BUILT-IN STRINGS FUNCTIONS IN C


C supports a wide range of functions, available in string.h library, that manipulate null-terminated strings:

# Function Description
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1>s2; greater than 0 if s1<s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
7 strlwr(s1); Returns the string with all lower-case letters of s1.
8 strupr(s1); Returns the string with all upper-case letters of s1.

The following example uses some of the above-mentioned functions:

Example 17.5: Built-in String Functions in C


/* Example_17_5.c: Built-in String Functions in C
------------------------------------------------------------------------
This program demonstrates the use of built-in functions for strings in C.
------------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 21-Nov-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>
#include <string.h>

int main()
{
char str1[6] = "Hello";
char str2[6] = "World";
char str3[12];
int len = 0;

// copy str1 into str3


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3);

// concatenates str1 and str2 and store result back into str1
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1);

// total lenghth of str1 after concatenation


len = strlen(str1);

7|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

printf("strlen(str1) : %d\n", len);

// all upper case letters


printf("strupr(str2) : %s\n", strupr(str2));

return 0;
}

// End of program
strcpy( str3, str2) : Hello
strcat( str1, str2): HelloWorld
Program Output
strlen(str1) : 10
strupr(str2) : WORLD

Answer: Paste your code here.

TASK 17.3: Smallest and Largest in a Series of Words [1 point]


Write a program that finds the smallest and largest in a series of
words. After the user enters the words, the program will determine
which words would come first (smallest) and last (largest) if the words
were listed in dictionary order. The program must stop accepting input
when the entered word is a four-letter word.
Please enter a word >> Elephant
Please enter a word >> Eagle
Please enter a word >> Dog
Please enter a word >> Tiger
Please enter a word >> Catfish
Please enter a word >> Dolphin
Please enter a word >> Spider
Sample Output
Please enter a word >> Zebra
Please enter a word >> Cat
Please enter a word >> Panther
Please enter a word >> Lion

Smallest word is Cat.


Largest word is Zebra.

8|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Answer:

PASSING STRINGS TO FUNCTIONS


Since string is a special case of arrays therefor it can be passed to a function in a similar way as arrays.

Example 17.6: Passing a String to Function in C


/* Example_17_6.c: Passing a String to Function in C
----------------------------------------------------------------------
This program implements a user-defined function that takes a string as
an input and returns the frequency of the characters requested.
----------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 22-Nov-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

// function declaration
int chFrequency(char str[], char character);

9|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int main()
{
char str[100], ch;
int chFreq = 0;

printf("Please enter the string: ");


fgets(str, sizeof(str), stdin);

printf("Please enter the character >>");


scanf(" %c", &ch);

// function call
chFreq = chFrequency(str, ch);

printf("\nCharacter \'%c\' appeared %d times in given string.", ch, chFreq);

return 0;
}

// function definition
int chFrequency(char str[], char character)
{
int freq = 0;

for (int i = 0; str[i] != '\0'; ++i)


{
if (character == str[i])
++freq;
}

return freq;
}

// End of program
Please enter the string: This is my first user-defined function
with string as parameter.
Program Output Please enter the character >>i

Character 'i' appeared 7 times in given string.

TASK 17.4: Is Palindrome? [1 point]


Write a function is_palindrome() that takes a string as an input and
returns if it is a palindrome or not. In main() ask user to enter the
string and pass it to the user-defined function. And print if the enter

10 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

string is a palindrome or not.


Please enter the string: rotator
Sample Output 1
You have entered a palindrome!
Please enter the string: butterfly
Sample Output 2
You have not entered a palindrome!

Answer:

TASK 17.5: User-defined String Functions [1 point]


Write user-defined functions that perform the tasks performed by the
following C built-in functions.
 strlen() -> string_length()
 strcpy() -> string_copy()
 strcat() -> string_concatenate()
 strupr() -> string_upper_case()
In main() take two strings from the user and by using these user-
defined functions, perform the string operations, and display the
output on computer screen.
Please enter string1 >> Quick Brown Fox
Please enter string2 >> Lazy Dog

string_length(string1): 15
Sample Output
string_copy (string3, string1): Quick Brown Fox
string_upper_case(str2): LAZY DOG
str4 = string_concatenate(string2, string1): Lazy Dog
Quick Brown Fox

11 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Answer:

ARRAY OF STRINGS
We can also create an array of string. Each slot of the array will contain a string and that can be of any size
with possibility of different string size in each array location. Let us discuss the example below.

Example 17.7: Planets of Solar System


/* Example_17_7.c: Planet of Solar System
----------------------------------------------------------------------
This program implements the concept of array of strings. It asks user
to enter a capital letter and return the planet names that start with
it.

12 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

----------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 21-Nov-2022.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
char planets[][8] = {"Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};
char firstLetter = ' ';
int count = 0;

printf("Please enter the first letter >> ");


scanf("%c", &firstLetter);

for (int i = 0; i < 9; i++)


{
if (planets[i][0]==firstLetter)
{
printf("%s begins with %c\n", planets[i], firstLetter);
count++;
}
}
if (count==0)
{
printf("No planet in Solar System starts with \"%c\".", firstLetter);
}

return 0;
}

// End of program
Please enter the first letter >> M
Program Output 1 Mercury begins with M
Mars begins with M
Please enter the first letter >> O
Program Output 2
No planet in Solar System starts with "O".

13 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

As you can see in the array of strings definition that number of rows of the planets array is omitted, as it is
obvious from the number of elements in the initializer, but we must specify the number of columns, i.e.,
maximum length of string.

char planets[][8] = {"Mercury", "Venus", "Earth",


"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto"};
The table below shows how the planets array will look like. Not all the strings were long enough to fill an
entire row of the array, therefor C language padded them with null characters. There is a bit of wasted space
in the array, since only three planets ("Mercury", "Jupiter", and "Neptune") have names long
enough to require eight characters including the terminating null character.
0 1 2 3 4 5 6 7
0 'M' 'e' 'r' 'c' 'u' 'r' 'y' '\0'
1 'V' 'e' 'n' 'u' 's' '\0' '\0' '\0'
2 'E' 'a' 'r' 't' 'h' '\0' '\0' '\0'
3 'M' 'a' 'r' 's' '\0' '\0' '\0' '\0'
4 'J' 'u' 'p' 'i' 't' 'e' 'r' '\0'
5 'S' 'a' 't' 'u' 'r' 'n' '\0' '\0'
6 'U' 'r' 'a' 'n' 'u' 's' '\0' '\0'
7 'N' 'e' 'p' 't' 'u' 'n' 'e' '\0'
8 'P' 'l' 'u' 't' 'o' '\0' '\0' '\0'

14 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

The inefficiency that appears in this example is common when working with strings, since most collections
of strings will be a mixture of long strings and short strings. In C language, we can tackle this problem by
simulating “rugged array type” by creating an array whose elements are pointers to strings.
TASK 17.6: Lexicographical Order [1 point]
Write a program that take 7 different strings from user and display
them on screen in lexicographical (dictionary) order. You must define a
2-D array of string for this problem.
Please enter the string1: grapes
Please enter the string2: bananas
Please enter the string3: apples
Please enter the string4: peaches
Please enter the string5: mangoes
Sample Output
Please enter the string6: papayas
Please enter the string7: pears

In Lexicographical Order: apples, bananas, grapes,


mangoes, papayas, peaches, pears.

15 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Answer:

Students are advised to fill the manual and submit it before the upcoming lab. Kindly rename the file as
‘MCT-242L_CP1_2022_LM17_XX’, where XX is your roll number. After completing the manual, turn it in Google Classroom.

16 | P a g e Computer Programming-I Lab

You might also like