Week 13
Week 13
Introduction
…. 'H'
's' '#'
'e' ''l'' 'f'
'l' 'd'
'o' 'y'
'' 'w'
'4' '7'
'o' '$'
'r' '_'
'l' 'e'
'd' '\0'
'g' 'd' '.' 'p' 'v' ….
str
Terminator
The Terminator
• Strings terminate with NULL character, signed
by '\0' (ascii code 0)
• This is a convention used to know where the
string ends
• It means that in order to hold a string of N
characters we need an array of length N + 1
• So the previous initialization is equivalent to
char str[] = {'b', 'l', 'a', 'b', 'l', 'a', '\0'};
String library
• Like in the case of stdio.h and math.h, we
have a special library for handling strings
• We should #include <string.h>
String library
• Functions:
– strlen(const char s[])
returns the length of s
– strcmp(const char s1[],
const char s2[])
compares s1 with s2
– strcpy(char s1[],
const char s2[])
copies to contents of s2 to s1
– strncpy(char s1[],
const char s2[], int n)
n is the maximum number of characters to be
appended.
Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
Character Analysis and
Conversion
Functions Description
(ctype.h)
isalpha Check if the argument is a letter
void main(void)
{
char line[81];
printf("Enter a line of text:\n");
gets(line);
printf("Blanc character occurs for: %d
time in the line.\n", spacecounter(line));
}
Solution
int spacecounter(char inputline[])
{
int i = 0;
int count = 0;
while (inputline[i] != '\0') {
if (inputline[i] == ' '){
count++;
}
i++;
}
return count
}
Exercise 13.2
• write a function that:
– gets a string and two chars
– the functions scans the string and replaces every
occurrence of the first char with the second one.
• write a program to test the above function
– the program should read a string from the user (no
spaces) and two characters, then call the function
with the input, and print the result.
• example
– input: “papa”, „p‟, „m‟
– output: “mama”
Solution (function)
void replace(char str[], char replace_what,
char replace_with)
{
int i;
int main(void)
{
char str[STRING_LEN + 1];
char replace_what, replace_with;
return 0;
}
Exercise 13.3
• Write a program that tests a
customer number to determine
whether it is in the proper
format(LLLNNNN with LLL are letters
and NNNN are digits).
Solution: testNum function
int testNum(char custNum[])
{
int count;
if (strlen(cusNum)!=7) return 0;
// Test the first three characters for alphabetic letters
for (count = 0; count < 3; count++)
{
if (!isalpha(custNum[count]))
return 0;
}
// Test the last 4 characters for numeric digits
for (count = 3; count < 7; count++)
{
if (!isdigit(custNum[count]))
return 0;
}
return 1;
}
Solution: main program
#include <stdio.h>
#include <ctype.h>
void main(void)
{
char customer[8];
printf("Enter a customer number with exact 7 characters
in the form LLLNNNN\n";
printf("LLL = letters and NNNN = numbers): ";
scanf("%s",customer);
if (testNum(customer))
printf("That's a valid customer number.\n";
else
{
printf("That is not the proper format of the
customer number.\nHere is an example: ABC1234\n");
}
}
Exercise 13.3
• Write your own replacement for the
standard strcpy() that comes with C
without using string.h
Solution
char *my_strcpy(char *destination, char
*source)
{
char *p = destination;
while (*source != '\0')
{
*p++ = *source++;
}
*p = '\0';
return destination;
}
Bài tập bổ sung
• Viết hàm trimRight(char a[]) loại bỏ tất cả
các ký tự trắng liền nhau ở cuối xâu a.
• Viết hàm trimLeft(char a[]) loại bỏ tất cả
các ký tự trắng liền nhau ở đầu xâu a.
• Viết hàm trimMiddle(char a[]) đưa tất cả
các dấu trắng liền nhau ở giữa xâu về 1.
• Test với xâu:
• “ Cong hoa xa hoi CNVN .“
Bài tập: Hàm chuẩn hóa tên
• Viết hàm thực hiện chuẩn hóa một tên
tiếng Việt như sau:
– Không có các dấu cách thừa
– Chữ cái bắt đầu các từ phải là Hoa, các chữ
cái còn lại là chữ thường.
– Hàm thao tác trực tiếp trên xâu đối số,
không trả về xâu mới dùng lệnh return
• Test hàm bằng chương trình đơn giản
• Ví dụ:” Tran hoa BINH .” “Tran
Hoa Binh.”
Exercise 13.4
• Write a program asks the user to
enter his or her first and last names,
separated by a space. Then print out
the first name.
• The program shoud use a function
which cuts off the last name off the
string in parameter.
Solution
#include <stdio.h>
#include <string.h>
void main(void)
{
char name[41];
printf("Enter your first and last names, separated
by a space:\n");
gets(name);
nameSlice(name);
printf("Your first name is: %s\n", name);
}
Solution
// This function accepts a character array as its
// argument. It scans the array looking
// for a space. When it finds one, it replaces it
// with a null terminator.
void main(void)
{
char prods[5][27] = {"TV127 31 inch Television",
"CD057 CD Player",
"TA877 Answering Machine",
"CS409 Car Stereo",
"PC655 Personal Computer"};
char lookUp[27], *strPtr = NULL;
int index;
printf("\tProduct Database\n\n");
printf("Enter a product number to search for: ");
scanf("%s",lookUp);
Solution
//Fill in here…
Exercise 13.7
• Write a program that accepts a string
from the user
and replaces all punctuation signs
(,.;:!?) with spaces
Solution (str_any.c)
char* str_any(char* str1, char* str2)
{
while (*str1 != '\0')
{
if (strchr(str2, *str1) != NULL) {
return str1;
}
++str1;
}
return NULL;
}
Solution
int main(void)
{
char* punc = ".,;:!?";
char s[MAX_LENGTH + 1];
char *p;
return 0;
}
Bài tập bổ sung – Mã hóa
• Phương pháp mã hóa cổ điển các văn
bản được thực hiện như sau:
a) Dịch ký tự sang k bước trong bảng chữ
cái, và xoay vòng tròn. Ví dụ: a -> c, b-
>d, z ->b. Việc giải mã được thực hiện
ngược lại.
– Viết hàm mã hóa và giải mã một xâu
ký tự với giá trị bước dịch chuyển tùy
biến ở dạng tham số.
– Sử dụng hàm trên để mã hóa một
đoạn văn bản nhập từ bàn phím sau
đó giải mã.
Bài tập bổ sung – Thống kê
tần suất
• Cho một đoạn văn bản, thống kê tần
suất xuất hiện của tất cả các ký tự là
chữ cái và chữ số.
Homework
• The number plate for motorcycles in
Hanoi is structured as follows:
DD-LDDDD.DD
• where D is a digit. L is a letter. The first
DD is in the range of 29 – 32.
• Write a function
checkValidNumberPlate(String s[]) that
return 1 if the number plate is valid and
0 if not. Test the function in a program,
which repeats asking user to input the
different number plates.
BTBosung – Shift function
• write a function that make all the
characters of a string shift left 1
position:
– « hello » « elloh »
• write a corresponding shift right
function.
– « hello » « ohell »
get Sub String
#include <string.h>
main(){
char from[10] = "12345678";
char *to;
to=strndup(from+2, 5);
}