Exercise Explain the following output, string st = \"hello\"; char c = st[1+2] +
ID: 3844966 • Letter: E
Question
Exercise Explain the following output, string st = "hello"; char c = st[1+2] + 3; cout << c;// prints o, explain cout << st.substr(2, 2);// prints ll, explain cout << st; st.insert(st.size() - 1, " n"); cout << st;//prints hell no, explain #include <iostream> using namespace std; int main(){ string words[2] = {"CS", "CUNYQC"}; string newst = words[0] + "1" + "11"; cout << newst << endl;//print CS111 cout << newst.size() << endl;//print 5 cout << newst[0] << endl;//first character of newst same as newst.at(i), print C //string is not an array to char, c-string is an array of characters ends with '' //write a loop to print every other character in words[1] for (int i = 0; i < words[1].size(); i+=2){ cout << words[1][i]; } cout << newst.substr(2); cout << words[1].substr(4); cout << words[1].substr(0, 4); //print out the second from last character string state = "NY"; //change string to N.Y. cout << state; return 0; }
Explanation / Answer
main1.cpp
#include <iostream>
using namespace std;
int main(){
string st = "hello";// st have 5 character starting from location 0 to 4
char c = st[1+2] + 3;
cout << c<<endl;// prints o, st[1+2]=st[3]=l, l+3 = 3rd character after l = 0
cout << st.substr(2, 2)<<endl;// prints ll, it will print substring at location 2,2 that is ll
cout << st<<endl;//it will print full string
st.insert(st.size() - 1, " n");//it will insert _n at location 5-1 = 4
cout << st<<endl;//prints hell no, it will print new string that is hell_no, _ is space
return 0;
}
Output :-
main2.cpp
#include <iostream>
using namespace std;
int main(){
string words[2] = {"CS", "CUNYQC"};
string newst = words[0] + "1" + "11";
cout << newst << endl;//print CS111
cout << newst.size() << endl;//print 5
cout << newst[0] << endl;//first character of newst same as newst.at(i), print C
//string is not an array to char, c-string is an array of characters ends with ''
//write a loop to print every other character in words[1]
for (int i = 0; i < words[1].size(); i+=2){
cout << words[1][i];
}
cout << newst.substr(2);
cout << words[1].substr(4);
cout << words[1].substr(0, 4);
//print out the second from last character
string state = "NY";
//change string to N.Y.
cout << state;
return 0;
}
Output :-
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.