please use the c++, finish the code CS 23001 Spring 2017 Page 2 of 5 M. Decker 4
ID: 3588860 • Letter: P
Question
please use the c++, finish the code
CS 23001 Spring 2017 Page 2 of 5 M. Decker 4. (20pts) Given the class definition below, implement the three methods: string (const char (constructs a new string with the value of a character array), length (returns the number of characters in the string) and operator+ (returns the concatenation of two strings). You can only use the provided methods and cannot use any built in functions or libraries. The class invariant must be maintained (null terminating character array). constint CAP = 100 ; /CLASS INV: str[length () 1 == 0 class string { private: char str[CAP]; public : String () { str[0] = 0; } string (const char[1); 1'A) Need to implement int length () const ; I/B) Need to implement string operator+ (const stringE) const; /C) Need to implementExplanation / Answer
header file :String.h
#ifndef STRING_H
#define STRING_H
const int CAP = 100;
//class inv: str[length()]==0
class String{
private :
char str[CAP];
public :
String () { str[0]=0;}
String (const char[]);
int length() const;
String operator+(const String&)const;
};
#endif /* STRING_H */
String.cpp
# include <iostream>
#include "String.h"
using namespace std;
int String::length() const{ // to find the length of the string
int i;
for(i=0;str[i]!='';++i);
return(i);
}
String::String(const char st[]){ //parameterized constructor
int i;
for(i=0;st[i]!='';i++){
str[i]=st[i];
}
str[i]='';
}
//to concatenate two strings
String String:: operator+(const String& temp)const{
String obj;
int i,j,k;
//for first string
for(i=0;str[i]!='';i++){
obj.str[i]=str[i];
}
//second string
for(j=i,k=0;temp.str[k]!='';k++,j++){
obj.str[j]=temp.str[k];
}
cout<<" The new string is : "<<obj.str;
return(obj);
}
Driverfile : main.cpp
#include <cstdlib>
# include "String.h"
# include <iostream>
using namespace std;
int main(int argc, char** argv) {
char ch1[100], ch2[100];
//accepting first string
cout<<"Enter the First String:";
cin.getline(ch1,100);
//accepting second string
cout<<"Enter the Second String:";
cin.getline(ch2,100);
//create object invokes the parameterized constructor
String s1(ch1);
String s2(ch2);
//create object invokes default constructor
String s3;
//display the length of the string
cout<<" The length of the first string :"<<s1.length();
cout<<" The length of the second string :"<<s2.length();
s3 = s1 + s2; //operator overloading to concatenate two strings
cout<<" The length of the new string is :"<<s3.length();
return 0;
}
sample output:
Enter the First String:hello
Enter the Second String:world
The length of the first string :5
The length of the second string :5
The new string is : helloworld
The length of the new string is :10
RUN SUCCESSFUL (total time: 4s)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.