Strings - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

Strings

Description:

... have enough memory space to assign the string, otherwise some chars will be lost. ... Input: chair diary boss circus fly dog church clue dish ... – PowerPoint PPT presentation

Number of Views:103
Avg rating:3.0/5.0
Slides: 45
Provided by: drbunyarit
Category:
Tags: strings

less

Transcript and Presenter's Notes

Title: Strings


1
Strings
Lecture11
IT050 - Introduction to Computers and Programming
Dr. Bunyarit Uyyanonvara IT Program, School of
IMT Sirindhorn International Institute of
Technology Thammasat University bunyarit_at_siit.tu.a
c.th 02 5013505 ext 2005 http//www.siit.tu.ac.t
h/bunyarit
2
String (general characteristic)
  • Text processing string processing
  • Basic data unit is not numbers but characters or
    strings of characters
  • Application word processing and text editors
  • What is string ?
  • Any sequence of characters enclosed in double
    quotes
  • Also called string constant
  • In C, print, printf , scanf functions are
    used for string processing
  • a char array string

3
String in C
  • A new data type is now considered, namely, the
    character string, which is used to represent a
    sequence of characters regarded as a single data
    item.
  • In C strings of characters are held as an array
    of characters, one character held in each array
    element.

4
String in C
  • In addition a special null character, represented
    by \0', is appended to the end of the string to
    indicate the end of the string.
  • Hence if a string has n characters then it
    requires an n1 element array (at least) to store
    it.

5
String in C
  • Thus
  • the character 'a' is stored in a single byte,
    whereas
  • the single-character string "a" is stored in
    two consecutive bytes holding the character a'
    and the null character.

6
String (an array of characters)
  • A string variable s1 could be declared as
    follows
  • char s10
  • char s
  • The string variable s1 could hold strings of
    length up to nine characters since space is
    needed for the final null character.

7
String (an array of characters)
  • In C, the string type is represented by char
    or an array of characters.
  • The standard library string.h provides functions
    for manipulating the string.

String The array of characters String pointer
to characters
8
Conceptual Check Point
  • What character is used to terminate a String ?
  • Is C the same as C ?
  • Which one is a character and which one is a
    string ?

9
String Initialization
  • Initialization
  • char m9 I like C
  • char m I like C
  • char m I, , l, i, k, e,
    ,C

l
i
C
\0
I
k
e
m0
m1
m2
m3
m4
m5
m6
m7
m8
10
String Initialization
char s30 "c programming " // ok,
preferred char s30 "c programming " //
ok, redundant char s30 c programming
// illegal char s30 c,p,i //
illegal char s30 S',I',I',T'
// ok, inconvenient char string_var30
// ok, not initialize char s c
//s0c,s1,s2, s30 // ok,
initialize char str20 Initial value //
ok, initialize
11
String (an array of characters)
  • Strings can be initialized at the time of
    declaration just as other variables are
    initialized.
  • For example
  • char s1 "example"
  • char s220 "another example"
  • would store the two strings as follows
  • s1 example\0
  • s2 another example\0????

12
String (an array of characters)
  • s1 example\0
  • In the first case the array would be allocated
    space for eight characters, that is space for the
    seven characters of the string and the null
    character.

13
String (an array of characters)
  • s2 another example\0????
  • In the second case the string is set by the
    declaration to be twenty characters long but only
    sixteen of these characters are set, i.e. the
    fifteen characters of the string and the null
    character.
  • Note that the length of a string does not include
    the terminating null character.

14
(No Transcript)
15
String assignment
  • We can also assign a string variable using these
    functions
  • char x , y
  • strcpy(x, "Snoopy")
  • sprintf(y, " PeterPan")

16
(No Transcript)
17
String Output
  • s indicates a place holder for a string.
  • printf(this a string s, y)
  • printf(X is s, x)

18
Null is the end of it
  • include ltvcl.hgt
  • include ltconio.hgt
  • include ltstdio.hgt
  • include ltstring.hgt
  • int main()
  • char x
  • strcpy(x,"Snoopy is not a cat")
  • x11 '\0'
  • printf("x s",x)
  • getch()

19
String Assignment
char s5"SIIT" char dept5, ddept char
name20 name Peter Pan" strcpy(name,Peter
Pan") strcpy(dept,"IT") printf("s s
s\n",d,s,dept) d strcpy(s,"EE") printf("s
s s s\n",name,d,s,dept) char c130,
c230This is new c1 string char s30 "c
programming " char str130 char
str strcpy(c1, c2) str strcat(s,"is
great!!") str1 strcat(s,"is great!!")
Make sure that you have enough memory space to
assign the string, otherwise some chars will be
lost.
20
In-Class Example
  • void main()
  • char first100, last100
  • int i
  • strcpy(first,"Peter")
  • sprintf(last, "Pan")
  • printf("my name is s, s\n", last,
    first)
  • for (i0 ilt5 i)
  • printf("s \n",last)
  • getch()

21
In-Class Example
  • See in-class example

22
Special functions for string
Prototype int sscanf( const char buffer, const
char format , argument ... ) purpose
converts string buffer into format
data. Example sscanf( 85 96.2
hello,d.3lfs,num,val,word) results
num85, val 96.2, word hello
23
Number 2 String
Prototype int sprintf( char buffer, const char
format , argument ... ) purpose converts
format data into string buffer. Example
sprintf(s,d/d/d, mon, day, year) results
if mon8, day23, year2001, s 8/23/2001
24
Frequently-Used String Functions
  • size_t strlen(const char s)
  • Computes the string length.
  • char strcpy(char s1, const char s2)
  • Copies the string s2 into s1. The value of s1 is
    returned.
  • int strcmp(const char s1, const char s2)
  • Return zero if string s1 is exactly the same as
    s2,
  • negative integer if s1 is less than s2, and
  • positive integer if s2 is less than s1.

25
Programming Example
main() char c130, c230 char s
"c" printf(\nString s is s and its
length is d,s, strlen(s)) strcpy(c1, "This
is new c1 string") printf("\nString c1 is
s,c1) strcpy(c2, c1) printf("\nString
c2 is s,c2) printf("\nCompare c1, c2 gives
d,strcmp(c1, c2)) printf("\nCompare c1, s
gives d,strcmp(c1, s)) printf("\nCompare
s, c1 gives d\n,strcmp(s, c1))
Output String s is c and its length is
3 String c1 is This is new c1 string String c2
is This is new c1 string Compare c1, c2 gives
0 Compare c1, s gives 115 Compare s, c1 gives
-115
26
Conceptual Check Point
  • What is the meaning of 0 ?
  • What is the meaning of 0, ?
  • What is the meaning of \0 ?
  • What is the meaning of 0 ?

27
Array of String
We can declare an array of String the same way we
declare an array of any other variables. char
month1210 January, February,
March, April, May, June, July,
August, September, October, November,
December
28
String Input/Output
  • function printf() and scanf() use format s to
    read input and print output string
  • function gets() is used to read a line of input
    string

char name110, name230 scanf(s,name1)
// Input Munlin gets(name2) // Input M.
Munlin, IT dept, SIIT printf(Your name is
s\n,name) // Output Munlin printf(Your name
is s\n,name2) // M. Munlin, IT dept, SIIT
name1
M
u
n
l
n
\0
?
?
?
i
29
String Functions
Prototype strlen(const char s) purpose
Computes the length of string s, excluding the
null terminated string (\0 or 0). Example
strlen(Munlin) results returns 6
Prototype char strcat(char s1, const char
s2) purpose append s2 to the end of s1, return
s1. Example s1 M. s3
strcat(s1,Munlin) result s1 s3 M. Munlin
30
String Functions
Prototype int strcmp(const char s1, const char
s2) purpose compare string s1 and s2, return
zero if string s1 is exactly the same as
s2, return negative integer if s1 is less than
s2, and return positive integer if s1 is larger
than s2. Example coasdfsdafp strcmp(IT,
ITS) result comp negative integer number
Prototype char strcpy(char s1, const char
s2) purpose Copies the string s2 into s1,
return s1. Example str2 strcpy(str1,SIIT) re
sults str2 str1SIIT
31
Using of String Functions
String s is c programming and its length is
14 String c1 is This is new c1 string String s
becomes c programming is great!! String c2 is
This is new c1 string Compare c1, c2 gives
0 Compare c1, s gives -1 Compare s, c1 gives 1
include ltstdio.hgt include ltstring.hgt int
main() char c130, c230 char s30
"c programming " printf("String s is s and
its length is d\n",s, strlen(s)) strcpy(c1,
"This is new c1 string") printf("String c1
is s\n",c1) strcat(s,"is great!!")
printf("String s becomes s\n",s)
strcpy(c2,c1) printf("String c2 is
s\n",c2) printf("Compare c1, c2 gives
d\n",strcmp(c1, c2)) printf("Compare c1, s
gives d\n",strcmp(c1, s)) printf("Compare
s, c1 gives d\n",strcmp(s, c1)) return 0
32
String Functions
Prototype char strncpy(char s1, const char
s2, int n) purpose Copies up to n characters
from s2 to s1, return s1. Example str2
strncpy(str1,SIIT,2) results str2 str1SI
Prototype char strncat(char s1, const char
s2, int n) purpose append up to n chars of s2
to the end of s1, return s1. Example s1 M.
s3 strncat(s1,Munlin,3) result
s1 s3 M. Mun
Prototype int strncmp(const char s1, const
char s2, int n) purpose compare the first n
characters of s1 and s2.
33
Character Operations
  • The standard library ctype.h provides functions
  • for manipulating the character.

char ch scanf(c,ch) // Input ch ch
getchar() // Input ch printf(Character is
c\n,ch) // Output ch putchar(ch) //
Output ch ch S // OK, char
assignment putchar(ch) // output
S putchar(T) // output T
34
Character functions
Prototype isalpha(ch) purpose return TRUE if
ch is an alphabet within A-Z ot a-z example c
isalpha(ch) // chM return true, ch5
return false
Prototype isdigit(ch) purpose return TRUE if
ch is a digit within 0-9 example d
isdigit(ch) // chM return false, ch5
return true
Prototype islower(ch) purpose return TRUE if
ch is an alphabet within a-z example c
islower(ch) // chM return false, chm
return true
Prototype isupper(ch) purpose return TRUE if
ch is an alphabet within A-Z example c
isupper(ch) // chM return true, chm
return false
35
Character functions
Prototype isspace(ch) purpose return TRUE if
ch is a white space (space, newline,
tab) example c isspace(ch) // ch\n
return true, chm return false
Prototype tolower(ch) purpose return lower
case character of ch, if possible example c
tolower(ch) // chM return m
Prototype toupper(ch) purpose return upper
case character of ch, if possible example c
toupper(ch) // chm return M
36
Conclusions
  • Character strings are represented by arrays of
    characters.
  • The string is terminated by the null character.
  • In declaring a string you must set the size of
    the array to at least one longer than required to
    hold the characters of the string to allow for
    this null character.

37
Exercises
  • 1. Write a program to create 100 by 200 array.
    Compute the sum of the elements in row 40.
  • 2. Write a program fragment to display the sum of
    the values in each row of a 5x3 array of double.
  • 3. Given the following declarations, answer the
    questions
  • char s55, s1010, s2020
  • cahr aday7Sunday
  • char another9 Saturday
  • 3.1 strncpy(s5,another,4) s54 \0
  • 3.2 strcpy(s10,aday3)
  • 3.3 strlen(another)
  • 3.4 strcpy(s20,aday) strcat(s20,another)

38
Exercises
4. Write a function isvowel(char ch) and
isconsonent(char ch) that return true if ch is
the character code for vowel or consonant
respectively. Hint use switch statement to check
for vowel. 5. What does the program fragment
display ? char x80 gorilla char y80
coffee strcpy(x,y) printf(s\ts\n,x,y)
39
Exercises
6. What does the program fragment display ? char
x80 gorilla char y80
coffee strcat(x,y) printf(s\ts\n,x,y)
7. Write a function strtoint() and strtodouble()
that converts string representations of numbers
to their numeric equivalents. prototype int
strtoint(char s) prototype double
strtodouble(char s) example i
strtoint(-8) // i -8 example d
strtodouble(-75.812) // d -75.812
40
Exercises
8. Write a program that takes nouns and forms
their plurals on the basis of these rules a. if
noun ends in y, remove y and add ies. B. if
noun ends in s, ch,sh, add es. C in all
other cases, just add s. Input chair diary
boss circus fly dog church clue
dish output chairs diaries bosses circuses
flies dogs churches clues dishes
41
Basic String Handling Functions
char stpcpy (const char dest,const char src)
-- Copy one string into another. int
strcmp(const char string1,const char string2) -
Compare string1 and string2 to determine
alphabetic order. char strcpy(const char
string1,const char string2) -- Copy string2 to
stringl. char strerror(int errnum) -- Get error
message corresponding to specified error number.
int strlen(const char string) -- Determine the
length of a string. char strncat(const char
string1, char string2, size_t n) -- Append n
characters from string2 to stringl. int
strncmp(const char string1, char string2,
size_t n) -- Compare first n characters of two
strings. char strncpy(const char string1,const
char string2, size_t n) -- Copy first n
characters of string2 to stringl . int
strcasecmp(const char s1, const char s2) --
case insensitive version of strcmp(). int
strncasecmp(const char s1, const char s2, int
n) -- case insensitive version of strncmp().
42
String Searching
char strchr(const char string, int c) -- Find
first occurrence of character c in string. char
strrchr(const char string, int c) -- Find last
occurrence of character c in string. char
strstr(const char s1, const char s2) --
locates the first occurrence of the string s2 in
string s1. char strpbrk(const char s1, const
char s2) -- returns a pointer to the first
occurrence in string s1 of any character from
string s2, or a null pointer if no character from
s2 exists in s1 size_t strspn(const char s1,
const char s2) -- returns the number of
characters at the begining of s1 that match s2.
size_t strcspn(const char s1, const char s2)
-- returns the number of characters at the
begining of s1 that do not match s2. char
strtok(char s1, const char s2) -- break the
string pointed to by s1 into a sequence of
tokens, each of which is delimited by one or more
characters from the string pointed to by s2.
char strtok_r(char s1, const char s2, char
lasts) -- has the same functionality as
strtok() except that a pointer to a string
placeholder lasts must be supplied by the caller.

43
Character conversions and testing ctype.h
Character testing int isalnum(int c) -- True if
c is alphanumeric. int isalpha(int c) -- True if
c is a letter. int isascii(int c) -- True if c
is ASCII . int iscntrl(int c) -- True if c is a
control character. int isdigit(int c) -- True if
c is a decimal digit int isgraph(int c) -- True
if c is a graphical character. int islower(int
c) -- True if c is a lowercase letter int
isprint(int c) -- True if c is a printable
character int ispunct (int c) -- True if c is a
punctuation character. int isspace(int c) --
True if c is a space character. int isupper(int
c) -- True if c is an uppercase letter. int
isxdigit(int c) -- True if c is a hexadecimal
digit
44
Character conversions and testing ctype.h
Character Conversion int toascii(int c) --
Convert c to ASCII . tolower(int c) -- Convert c
to lowercase. int toupper(int c) -- Convert c to
uppercase.
Write a Comment
User Comments (0)
About PowerShow.com