question is on picture 2. Chapter 3 - Exercise 10 3-10 a. Write a program that w
ID: 3902523 • Letter: Q
Question
question is on picture 2.
Chapter 3 - Exercise 10 3-10 a. Write a program that will input three c-strings into an array of c-strings. Print only those that end in "es" or begin in 'yan. Use the following First, use a c-string function to find the length so you know where the last two characters are, then compare the last two characters separately. Second, use a c-string function to compare, all at once, just the first three characters in the c-string (a function similar to stremp, but that will only compare a certain number of characters) You will search two different ways. Use for loops to fill up the array and to loop through the c-strings for the searches b. Use string objects instead of c-strings. Input three strings into an array of strings. Again, use the following First, use a function to find the length for the end comparisons, then again compare the last two characters separately Second, use a string function to take a sub-string of the first three characters for the beginning comparison all at onceExplanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
Code for 3a)
===========
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
char str[3][15]; //3 strings each of max length 15
int len;
//input strings
cout << "Enter 3 strings: " << endl;
for(int i = 0 ;i < 3; i++)
{
cout << "string " << (i+1) << ": ";
cin.getline(str[i], 15);
}
//check and output
for(int i = 0; i < 3;i++)
{
if(strncmp(str[i], "yan", 3) == 0) //begins with "yan"
cout << "Begins with "yan": " << str[i] << endl;
else
{
int len = strlen(str[i]);
if(str[i][len-2] == 'e' && str[i][len-1] == 's') //check if ends with "es"
cout << "Ends with "es": " << str[i] << endl;
}
}
}
Code for 3b)
===========
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string str[3]; //3 strings
//input strings
cout << "Enter 3 strings: " << endl;
for(int i = 0 ;i < 3; i++)
{
cout << "string " << (i+1) << ": ";
getline(cin, str[i]);
}
//check and output
for(int i = 0; i < 3;i++)
{
if(str[i].substr(0, 3) == "yan") //begins with "yan"
cout << "Begins with "yan": " << str[i] << endl;
else
{
int len = str[i].length();
if(str[i][len-2] == 'e' && str[i][len-1] == 's') //check if ends with "es"
cout << "Ends with "es": " << str[i] << endl;
}
}
}
output
====
Enter 3 strings:
string 1: apples
string 2: yankfdk
string 3: test
Ends with "es": apples
Begins with "yan": yankfdk
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.