In: Computer Science
Must be in C++ and we can not use STR[] we must use STR.at()
Write a program that:
Example 1:
Enter name: Grace Hopper Index of last character: 11 Last 3 characters of first name: ace First 3 characters of last name: Hop
Example 2:
Enter name: Dorothy J. Vaughan Index of last character: 17 Last 3 characters of first name: thy First 3 characters of last name: Vau
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userFirstname;
string userLastname;
string userMiddlename;
cout << "Enter Name: ";
cin >> userFirstname;
cin >> userMiddlename;
cin >> userLastname;
cout << userFirstname << userMiddlename
<< userLastname << endl;
cout << "Index of last character: ";
cout << ((userFirstname.size() +
userLastname.size()) - 1);
cout << endl;
cout << "Last 3 characters of first name:
";
cout << (userFirstname.at(userFirstname.size() -
3)) << (userFirstname.at(userFirstname.size() - 2)) <<
(userFirstname.at(userFirstname.size() - 1)) << endl;
cout << "First 3 characters of last name:
";
cout << userLastname.at(1) <<
userLastname.at(2) << userLastname.at(3) << endl;
return 0;
}
// do comment if any problem arises
//there is some problem in your input method because middle name is optional so use getline()
#include <iostream>
#include <string>
using namespace std;
// this method finds first space that occured in given string
int first_space(string temp)
{
for (int i = 0; i < temp.size(); i++)
{
if (temp.at(i) == ' ')
return i;
}
return -1;
}
// this method finds last space that occured in given string
int last_space(string temp)
{
int last = -1;
for (int i = 0; i < temp.size(); i++)
{
if (temp.at(i) == ' ')
last = i;
}
return last;
}
int main()
{
string username;
cout<<"Enter Name: ";
getline(cin, username);
cout << username << endl;
cout << "Index of last character: ";
cout << (username.size() - 1)<<endl;
cout << "Last 3 characters of first name: ";
// find ending index of first name
int first=first_space(username);
// find starting index of last name
int last=last_space(username);
cout << (username.at(first - 3)) << (username.at(first - 2)) << (username.at(first - 1)) << endl;
cout << "First 3 characters of last name: ";
cout << username.at(last+1) << username.at(last+2) << username.at(last+3) << endl;
return 0;
}
Output: