0% found this document useful (0 votes)
29 views23 pages

Strings C++

The document provides an overview of C++ strings and character arrays, explaining the differences between C-strings and C++ strings, including their declaration, operations, and memory management. It highlights key string operations in C++, such as copying, concatenation, comparison, and length retrieval, emphasizing the simplicity and safety of using the std::string class compared to C-style strings. Additionally, it covers input and output functions for strings in C++, recommending the use of getline for safe input and cout for output.

Uploaded by

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

Strings C++

The document provides an overview of C++ strings and character arrays, explaining the differences between C-strings and C++ strings, including their declaration, operations, and memory management. It highlights key string operations in C++, such as copying, concatenation, comparison, and length retrieval, emphasizing the simplicity and safety of using the std::string class compared to C-style strings. Additionally, it covers input and output functions for strings in C++, recommending the use of getline for safe input and cout for output.

Uploaded by

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

Computer Programming:

C++ language

Strings :)
C++-Strings OR Character Arrays

• Character array: An array whose components are


of type char

• String: A sequence of zero or more characters


enclosed in double quote marks (e.g., “hello”)

• Internally (by the compiler) C++ stings are


terminated with null (‘\0’) in memory
» (the last character in a string is the null-character
C++-String OR Character-Arrays

• We have learned that the elements of an array


can be just about anything
• Consider an array whose elements are all
characters
• Such type of an array is called a C-String
C++-Strings OR Character Arrays
char str[80] = “Amanuensis”
C-Strings OR Character Arrays

• There is a difference between 'A' and "A"


– 'A' is the character A
– "A" is the string A

• Because strings are terminated with null, "A"


represents two characters, 'A' and '\0‘
• Similarly, "Hello" contains six characters, 'H',
'e', 'l', 'l', 'o', and '\0'
Declaration of C++ Strings

Similar to declaration of any array


// no initialization
string title;

// initialized at declaration with a


string
string title2 = "QUEST NAWABSHAH";

// initialized with list of char values


string chList = "abcd";
Declaration of C++ Strings
In C++ strings you don’t need [10] (or any size) because std::string manages
its own size dynamically.
• In C (char array):

char chList[10] = {'a', 'b', 'c', 'd'};


● ➝ You must give a size, because it’s literally an array of characters in
memory.

• In C++ (std::string):

string chList = {'a', 'b', 'c', 'd'};


● ➝ No size needed. The string just becomes "abcd".

So ✅ in your C++ notes, drop the [10].


C-Strings: Example-1
#include<iostream>
using namespace std;

int main()
{
char name[]="Yasir";
int i=0;
while(i<=4)
{
cout << name[i];
i++;
}
cout << endl;
return 0;
}
C++ offers four main operations on strings
C++ String Operations (Modern Way)
In C, string handling relies on functions like strcpy, strcat, strcmp, and strlen.
In C++, the string class provides built-in operators and functions that make these
tasks easier and safer.

● Copy (= operator) → Assign one string directly to another.

● Concatenation (+ operator or +=) → Join two strings together.

● Comparison (==, !=, <, >) → Compare strings alphabetically.

● Length (.length() or .size()) → Get the number of characters in a string.

👉 Unlike C, there’s no need for separate library functions—the string class handles
these operations naturally.
strcpy
String Copy in C++
● In C → strcpy(destination, source) is used to copy the contents of one
string into another.

● In C++ → we simply use the assignment operator (=) with string objects.

● = operator → directly assigns one string to another.

Example:
string str;
str = "hello world"; // assigns value directly

👉 This is much simpler and safer than strcpy() in C.


Example with strcpy
#include <iostream>
#include <string>
using namespace std;
int main() {
string x = "Example with strcpy";
string y;
cout << "The string in x is: " << x << endl;
// Copy string
y = x;
cout << "The string in y is: " << y << endl;
return 0;
}
String Concatenation in C++
String Concatenation in C++
● In C → strcat(destination, source) is used to append one string to
another.

● In C++ → we use the + operator or += operator with string objects.

● + operator → creates a new combined string.

● += operator → adds (appends) text to the existing string.

Example:

● "a big " + "hello world" → gives "a big hello world"
String Concatenation in C++
#include <iostream>
#include <string>
using namespace std;

int main()
{
string x = "Example with strcat";
string y = " which stands for string concatenation";
cout << "The string in array x is " << x << endl;
x = x + y; // Simple concatenation using + operator
cout << "The string in array x is " << x << endl;
return 0;
}
📌 length() in C++ Strings

length() (or size()) gives the number of characters in a string.

It does not count the null character \0 (because C++ string doesn’t need
it).

● Example:

string str = "tttt";


cout << str.length(); // Output: 4

✔ So, "tttt" has length 4, not 5.


Example with length()
#include <iostream>
#include <string>
using namespace std;

int main() {
string arr = "QUEST";
int len1, len2;

len1 = arr.length(); // length of arr


len2 = string("QUEST NAWABSHAH").length(); // length of literal

cout << "string = " << arr << " length = " << len1 << endl;
cout << "string = " << "QUEST NAWABSHAH" << " length = " << len2 << endl;

return 0;
}
Example with length()
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i, count;
string x = "tommy tucket took a tiny ticket";
count = 0;
for (i = 0; i < x.length(); i++)
{
if (x[i] == 't') count++;
}
cout << "The number of ts in " << x << " is " << count <<
endl;
return 0;
}
Vowels Example with lenght
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i, count;
string x = "tommy tucket took a tiny ticket";
count = 0;
for (i = 0; i < x.length(); i++)
{
if ((x[i] == 'a')||(x[i]=='e')||(x[i]=='i')||(x[i]=='o')||(x[i]=='u'))
count++;
}
cout << "The number of vowels in " << x << " is " << count <<
endl;
return 0;
}
No of Words Example with length()
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i, count;
string x = "tommy tucket took a tiny ticket ";
count = 0;
for (i = 0; i < x.length(); i++)
{
if (x[i] == ' ') count++;
}
cout << "The number of words in " << x << "is " << count+1 <<
endl;
return 0;
}
.comapre()
stringa.compare(stringb)
* Compares stringa and stringb alphabetically
* Returns a negative value if stringa precedes stringb
alphabetically
* Returns a positive value if stringb precedes stringa
alphabetically
* Returns 0 if they are equal
* Note lowercase characters are greater than Uppercase
* A=65 and a=97

// Alternative: Use comparison operators


stringa == stringb // equal
stringa < stringb // stringa precedes stringb
stringa > stringb // stringb precedes stringa
Example
#include <iostream>
with strcmp
#include <string>
using namespace std;

int main()
{
string x = "cat";
string y = "cat";
string z = "dog";

if (x == y)
cout << "The string in array x " << x << " is equal to that in " << y << endl;

if (x != z)
{
cout << "The string in array x " << x << " is not equal to that in z " << z << endl;
if (x < z)
cout << "The string in array x " << x << " precedes that in z " << z << endl;
Example with strcmp
else
cout << "The string in array z " << z << " precedes that in x " << x << endl;
}
else
cout << "they are equal" << endl;

return 0;
}
In C, strings are stored as character arrays (char[]) and the equality operator ==
only compares memory addresses, not the actual contents of the string. That’s
why functions like strcmp() are required to compare characters one by one.

In C++, the std::string class was introduced, which overloads the comparison
operators (==, !=, <, >, etc.) to perform lexicographical (alphabetical) content
comparison directly. This makes the code simpler, safer, and more readable.

👉 Therefore, in modern C++ we use simple operators like x == y instead of


strcmp(x,y) == 0.
Input output functions of characters and
strings
✅ C++ (Modern way)
● cin >> str; → input one word (stops at space).

● getline(cin, str); → input a full sentence (with spaces).

● cout << str; → output / print text (same line).

● cout << str << endl; → output / print text and move to next
line.

👉 Rule of thumb:
In C++ always use getline() for input and cout for output.
They are safe, simple, and work with std::string.
Input output functions of characters and
strings
#include <iostream>
#include <string>
using namespace std;

int main() {
string name;

cout << "Enter your full name: ";


getline(cin, name); // safe input for full name with spaces

cout << "Hello!" << endl;


cout << name << endl; // print the name

return 0;
}

You might also like