-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14-string_operations.cpp
More file actions
111 lines (82 loc) · 2.48 KB
/
14-string_operations.cpp
File metadata and controls
111 lines (82 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//The + operator can be used between strings to add them together to make a new string. This is called concatenation:
#include <iostream>
#include <string>
using namespace std;
void main() {
string firstName = "John "; // declaring a string called firstname
string lastName = "Doe"; // declaring a string called lastname
string fullName = firstName + lastName; // concatenating firstname and lastname using + operator and storing in fullname
cout << fullName; // printing fullname
}
//Appending a string
#include <iostream>
#include <string>
using namespace std;
void main() {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName); // using the append() method to append last name to firstname.
cout << fullName;
}
// to get length of a string use the method length()
#include <iostream>
#include <string>
using namespace std;
void main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
}
// or you can use the size() method.
#include <iostream>
#include <string>
using namespace std;
void main() {
string txt = "anaondnwoiandaoinwn";
cout << "The length of the txt string is:" << txt.size();
}
//Accessing strings
// you can access the string by referring to it's index number eg: [0].
#include <iostream>
#include <string>
using namespace std;
void main() {
string myString = "Hello";
cout << myString[0]; //this will output the character 'H'.
}
//changing a character in the string
#include <iostream>
#include <string>
using namespace std;
void main() {
string myString = "Hello";
myString[0] = 'J';
cout << myString; // outputs Jello instead of Hello.
}
// user inputting strings
#include <iostream>
#include <string>
using namespace std;
void main() {
string firstName;
cout << "Type your first firstname: ";
cin >> firstName;
cout << "your first name is: " << firstName;
}
// here cin will consider a whitespace " " as a breaking character hence we use getline(), with cin as the first parameter.
#include <iostream>
#include <string>
using namespace std;
void main() {
string firstName;
cout << "Type your first firstname: ";
getline(cin, firstName);
cout << "your first name is: " << firstName;
}
//Note: if you ommit using namespace std the code will look like this:
#include <iostream>
#include <string>
void main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}