3-10b. Modify exercise 3-10 part a into exercise 3-10 part b. Use string objects
ID: 3582106 • Letter: 3
Question
3-10b. Modify exercise 3-10 part a into exercise 3-10 part b. Use string objects instead of c-strings. Input three strings into an array of strings. Again, use loops and the following:
string str[3];
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 once.
*3-10a is below*
#include <stdio.h>
#include <string.h>
int last_cmp(char name_array[]) {
int length = strlen(name_array);
if (name_array[length - 2] == 's' & name_array[length - 3] == 'e')
return 1;
}
int first_cmp(char name_array[]) {
if (name_array[0] == 'y' & name_array[1] == 'a' & name_array[2] == 'n')
return 1;
}
void main()
{
char name[3][100], i = 1;
for (i = 0; i<3; i++) {
printf("Enter 3 words: ");
fgets(name[i], 100, stdin);
}
for (i = 0; i<3; i++) {
if (last_cmp(name[i]) == 1)
printf("String ends with es: %s", name[i]);
if (first_cmp(name[i]) == 1)
printf("String starts with yan: %s", name[i]);
}
}
Explanation / Answer
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int last_cmp(string name_array) {
int length = name_array.length();
if (name_array[length - 1] == 's' & name_array[length - 2] == 'e')
return 1;
}
int first_cmp(string name_array) {
string s = name_array.substr(0,3);
if (s=="yan")
return 1;
}
int main()
{
string name[3];
int i;
for (i = 0; i<3; i++) {
printf("Enter 3 words: ");
cin>>name[i];
}
for (i = 0; i<3; i++) {
if (last_cmp(name[i]) == 1)
cout<<"String ends with es "<<name[i]<<endl;
if (first_cmp(name[i]) == 1)
cout<<"String starts with yan "<<name[i]<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.