C-String Storage .A standard array: char s[10]; If s contains string "Hi Mom",stored as: ◆Display,page370 s[ol s[i] s[2] s[3】 s4] s[s] s[6] sl7l s[8] sl9] H M 0 m o 2 Copyright 2006 Pearson Addison-Wesley.All rights reserved. 9-6
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-6 C-String Storage ¨ A standard array: char s[10]; ¨If s contains string "Hi Mom" , stored as: ¨Display, page 370
C-String Initialization Can initialize c-string: char myMessage[20]"Hi there."; Needn't fill entire array Initialization places "\O"at end ◆Can omit array-size: char shortString[]"abc"; Automatically makes size one more than length of quoted string ◆NOT same as: char shortString {"a","b","c"}; Copyright 2006 Pearson Addison-Wesley.All rights reserved. 97
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-7 C-String Initialization ¨ Can initialize c-string: char myMessage[20] = "Hi there."; ¨ Needn’t fill entire array ¨ Initialization places "\0" at end ¨ Can omit array-size: char shortString[] = "abc"; ¨ Automatically makes size one more than length of quoted string ¨ NOT same as: char shortString[] = {"a" , "b" , "c"};
C-String Indexes ◆Ac-string IS an array Can access indexed variables of: char ourString[5]"Hi"; ◆ourString[o]is"H" ◆ourString[1]is"i ◆ourString[2]is"n0" +ourString[3]is unknown ourString[4]is unknown Copyright 2006 Pearson Addison-Wesley.All rights reserved. 9-8
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-8 C-String Indexes ¨ A c-string IS an array ¨ Can access indexed variables of: char ourString[5] = "Hi"; ¨ourString[0] is "H" ¨ourString[1] is "i" ¨ourString[2] is "\0" ¨ourString[3] is unknown ¨ourString[4] is unknown
C-String Index Manipulation Can manipulate indexed variables char happyString[7]="DoBeDo"; happyString[6]"Z"; ◆Be careful! +Here,"\O"(null)was overwritten by a "Z"! If null overwritten,c-string no longer "acts"like c-string! Unpredictable results! Copyright006 Pearson Addison-Wesley.All rights reserved. 9-9
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-9 C-String Index Manipulation ¨ Can manipulate indexed variables char happyString[7] = "DoBeDo"; happyString[6] = "Z"; ¨Be careful! ¨Here, "\0" (null) was overwritten by a "Z"! ¨ If null overwritten, c-string no longer "acts" like c-string! ¨Unpredictable results!
Library ◆Declaring c-strings Requires no C++library Built into standard C++ ◆Manipulations Require library <cstring> Typically included when using c-strings Normally want to do "fun"things with them Copyright 2006 Pearson Addison-Wesley.All rights reserved. 9-10
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-10 Library ¨ Declaring c-strings ¨Requires no C++ library ¨Built into standard C++ ¨ Manipulations ¨Require library <cstring> ¨Typically included when using c-strings ¨Normally want to do "fun" things with them