Lab - Strings
Lab - Strings
Lab – Strings
Tutorial Exercises:
1. Characters in a String
Write a program to ask the user to input a string, which may contain spaces, then do the
following tasks
a. Count for the number of alphabet letters, replace the lowercase characters by
uppercase and vice versa.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[SIZE]; //store maximum 99 characters
//Qa.
printf("Enter a string: ");
scanf("%[^\n]s", str);
int count = 0;
for (int i = 0; str[i] != '\0'; i++){
if ( isalpha(str[i]) ) {
count ++; //count number of alphabet characters
return 0;
}
b. Calculate and print out the sum of all digits in the string. For example, if the user input
“Hello 1a2b3c”, it will print out value 6.
c. Reverse it (modify the string) without using any extra string. For example, if the user
inputs "Good morning" then it becomes "gninrom dooG".
2. Word Count
A word is a sequence of characters with no whitespace characters. Count the number of words
in a given sentence. For example, this sentence has 7 words.
1
RMIT Classification: Trusted
a. Get 4 full names print out the first names in one line as below.
b. Sort the full names in alphabetical order.
Sample Run:
Enter full name 1: John Doe
Enter full name 2: Andrew Smith
Enter full name 3: Mike James Austin
Enter full name 4: Harry Potter
Sorted names:
Andrew Smith
Harry Potter
John Doe
Mike James Austin
Self-practice Exercises:
1. Input your birthdate in “dd/mm/yyyy” format, and current year, then print out your age.
2. Enter a list of full names, and a search keyword, then print out all names containing it.
Sample Run:
Enter full name 1: Andrew John Smith
Enter full name 2: John Doe
Enter full name 3: Minh Van Nguyen