0% found this document useful (0 votes)
8 views32 pages

9.the String Class

The document provides an overview of C-strings in C++, detailing their definition, initialization, input methods, and various operations such as copying and concatenation. It also covers the use of C-strings as class members and introduces the C++ string class, highlighting its advantages and functionalities. Additionally, the document lists library functions for working with C-strings and explains string operators and member functions.

Uploaded by

komal komal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

9.the String Class

The document provides an overview of C-strings in C++, detailing their definition, initialization, input methods, and various operations such as copying and concatenation. It also covers the use of C-strings as class members and introduces the C++ string class, highlighting its advantages and functionalities. Additionally, the document lists library functions for working with C-strings and explains string operators and member functions.

Uploaded by

komal komal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

C-Strings

Copyright © 2012 Pearson Education, Inc.


C-Strings

• C-string: sequence of characters stored in


adjacent memory locations and
terminated by NULL character
• String literal (string constant): sequence of
characters enclosed in double quotes " " :
"Hi there!"
H i t h e r e ! \0

Copyright © 2012 Pearson Education, Inc.


C-Strings
• Array of chars can be used to define storage for
string:
const int SIZE = 20;
char city[SIZE];

• Leave room for NULL at end


• Can enter a value using cin or >>
– Input is whitespace-terminated
– No check to see if enough space

Copyright © 2012 Pearson Education, Inc.


Initializing C-Strings
char mystring[ ] = "my name";
OR

char mystring[ ] = { 'm', 'y', ' ', 'n', 'a', 'm', 'e'};

char mystring[ ]; //error: size must be specified


mystring = "my name";
//error: expression must be modifiable lvalue
mystring[ ]="my name";
//error: const char* cannot be assigned to char.

Copyright © 2012 Pearson Education, Inc.


Taking c-string input
char inputstring[20];
cout<<"enter a string without spaces"<<endl;
cin >> inputstring;
//does not handle spaces and buffer overflow
cout << "you entered " << inputstring << endl;
cout << "enter a string without spaces" << endl;
cin >> setw(20) >> inputstring;
//handles buffer overflow, not more than 100 characters
cout << "you entered " << inputstring << endl;

Copyright © 2012 Pearson Education, Inc.


Taking c-string input
char inputstring2[20];
cout << "enter a string with spaces" << endl;
cin.get(inputstring2, 20); //reads string with spaces
cout << "you entered " << inputstring2 << endl;

cout << "enter multiple lines ending at $" << endl;


cin.get(inputstring2, 20, '$');
//by default third argument is \n
cout << "you entered " << inputstring2 << endl;
Copyright © 2012 Pearson Education, Inc.
Copying c-strings hard way
char sourcestring[]="i am source";
char deststring[50];
int length = strlen(sourcestring);
cout << "length of source string" << length << endl;
for ( i = 0; i < length; i++)
deststring[i]=sourcestring[i];
deststring[i] = '\0';
cout << sourcestring << endl;
cout << deststring << endl;
Copyright © 2012 Pearson Education, Inc.
copying string easy way

char newstring[ ] = "i am easy";


char deststring[50];

strcpy_s(deststring, newstring);
cout << deststring << endl;

Copyright © 2012 Pearson Education, Inc.


concatenating strings

char str1[80] = "tomato";


char str2[80] = "ketchup";
cout << str1 << endl;
cout << str2 << endl;

strcat_s(str1, str2);
cout << str1 << endl;

Copyright © 2012 Pearson Education, Inc.


Array of C-strings
const int elements=5;
const int elementlen=10;
char arrstrings[elements][elementlen] =
{ "abc","def","ghi","jkl","mno"};
//Array of strings as multidimentionsal array of chararcters
for (int j = 0; j<elements; j++)
cout << arrstrings[j] << endl;
//display every string

Copyright © 2012 Pearson Education, Inc.


C-Strings as class members
class student {
char name[20];
int rollnum;
public:
student();
student(char [], int );
void set(char[], int);
void display();
};
Copyright © 2012 Pearson Education, Inc.
C-Strings as class members
student::student() {
strcpy_s(name, "");
rollnum = 0;
}
student::student(char n[], int r) {
//name = n; error: expression must be a modifiable lvalue
strcpy_s(name, n);
rollnum = r;
}
Copyright © 2012 Pearson Education, Inc.
C-Strings as class members
void student::set(char n[], int r) {
strcpy_s(name, n);
rollnum = r;
}
void student::display() {
cout << "name is "<<name<<endl;
cout << "roll number is " << rollnum << endl;
}

Copyright © 2012 Pearson Education, Inc.


C-Strings as class members
int main() {
student s1("maria", 123);
s1.display();
student s2;
s2.display();
s2.set("saba", 456);
s2.display();
}

Copyright © 2012 Pearson Education, Inc.


Library Functions for Working with
C-Strings

Copyright © 2012 Pearson Education, Inc.


Library Functions for Working
with C-Strings
• Require the cstring header file

• Functions take one or more C-strings as


arguments. Can use:
– C-string name
– pointer to C-string
– literal string

Copyright © 2012 Pearson Education, Inc.


Library Functions for
Working with C-Strings
Functions:
– strlen(str): returns length of C-string str
char city[SIZE] = "Missoula";
cout << strlen(city); // prints 8
– strcat(str1, str2): appends str2 to the
end of str1
char location[SIZE] = "Missoula, ";
char state[3] = "MT";
strcat(location, state);
// location now has "Missoula, MT"

Copyright © 2012 Pearson Education, Inc.


Library Functions for
Working with C-Strings
Functions:
– strcpy(str1, str2): copies str2 to str1

const int SIZE = 20;


char fname[SIZE] = "Maureen", name[SIZE];
strcpy(name, fname);

Note: strcat and strcpy perform no bounds


checking to determine if there is enough space
in receiving character array to hold the string it
is being assigned.

Copyright © 2012 Pearson Education, Inc.


More About the C++ string
Class

Copyright © 2012 Pearson Education, Inc.


The C++ string Class
• Special data type supports working with strings
• #include <string>
• Can define string variables in programs:
string firstName, lastName;
• Can receive values with assignment operator:
firstName = "George";
lastName = "Washington";
• Can be displayed via cout
• Use cin >> to read an item into a string

Copyright © 2012 Pearson Education, Inc.


Assigning string objects
string s1("Man"); //initialize
string s2 = "Beast"; //initialize
string s3;
s3 = s1; //assign
cout << "s3 = "<<s3 << endl;
s3 = "Neither " + s1 + " nor "; //concatenate
s3 += s2; //concatenate
cout << "s3 = "<<s3 << endl;
s1.swap(s2); //swap s1 and s2
cout<<s1 << " nor " << s2 << endl;

Copyright © 2012 Pearson Education, Inc.


Input/output with string objects
string full_name, nickname;
cout << "Enter your full name : ";
getline(cin, full_name);
//reads embedded blanks
cout << "Your full name is : "<< full_name << endl;

Copyright © 2012 Pearson Education, Inc.


Input/output with string objects
string greeting("Hello, ");
cout << "Enter your nickname : ";
cin >> nickname;
//input to string object
greeting += nickname;
//append name to greeting
cout << greeting << endl;
//output: “Hello, Jim”

Copyright © 2012 Pearson Education, Inc.


Input/output with string objects
string address;
cout << "Enter your address on separate
lines terminate with ‘$’\n ";

getline(cin, address, '$');


//reads multiple lines
cout << "Your address is : " << address <<
endl;

Copyright © 2012 Pearson Education, Inc.


string Comparison
• Can use relational operators directly to compare string
objects:
string str1 = "George",
str2 = "Georgia";
if (str1 < str2)
cout << str1 << " is less than "
<< str2;
• Result is true or false

Copyright © 2012 Pearson Education, Inc.


Other Definitions of C++
strings
Definition Meaning
string name; defines an empty string object
string myname("Chris"); defines a string and initializes it
string yourname(myname); defines a string and initializes it
string aname(myname, 3); defines a string and initializes it with first 3
characters of myname

string verb(myname,3,2); defines a string and initializes it with 2


characters from myname starting at position
3

string noname('A', 5); defines string and initializes it to 5 'A's

Copyright © 2012 Pearson Education, Inc.


string Operators
OPERATOR MEANING
>> extracts characters from stream up to whitespace, insert
into string
<< inserts string into stream
= assigns string on right to string object on left
+= appends string on right to end of contents on left
+ concatenates two strings
[] references character in string using array notation
>, >=, <, relational operators for string comparison. Return true or
<=, ==, != false

Copyright © 2012 Pearson Education, Inc.


string Operators
string word1, phrase;
string word2 = " Dog";
cin >> word1; // user enters "Hot Tamale"
// word1 has "Hot"
phrase = word1 + word2; // phrase has
// "Hot Dog"
phrase += " on a bun";
for (int i = 0; i < 16; i++)
cout << phrase[i]; // displays
// "Hot Dog on a bun"

Copyright © 2012 Pearson Education, Inc.


Copyright © 2012 Pearson Education, Inc.
string Member Functions
• Are behind many overloaded operators
• Categories:
– assignment: assign, copy, data
– modification: append, clear, erase, insert,
replace, swap
– space management: capacity, empty,
length, resize, size
– substrings: find, substr
– comparison: compare
• See Table 10-7 for a list of functions

Copyright © 2012 Pearson Education, Inc.


string Member Functions

string word1, word2, phrase;


cin >> word1; // word1 is "Hot"
word2.assign(" Dog");
phrase.append(word1);
phrase.append(word2); // phrase has "Hot Dog"
phrase.append(" with mustard relish", 13);
// phrase has "Hot Dog with mustard"
phrase.insert(8, "on a bun ");
cout << phrase << endl; // displays
// "Hot Dog on a bun with mustard"

Copyright © 2012 Pearson Education, Inc.


Copyright © 2012 Pearson Education, Inc.

You might also like