void append(char*& s, const char ch) { /* Appends the character ch to the c-stri
ID: 3740280 • Letter: V
Question
void append(char*& s, const char ch)
{
/*
Appends the character ch to the c-string s.
That is ch is added to the end of s
The parameter s is assumed to be a dynamic array (NOT a static one)
*/
}
void append(char*& s1, const char* s2)
{
/*
Appends all the characters of s2 to s1
The parameter s1 is assumed to be a dynamic array (NOT a static one)
*/
}
//Test append function (appending a character to c-string)
cout << endl;
char* s2 = new char[1];
s2[0] = '';
cout << "Given the c-string " << s2 << endl;
ch = 'a';
append(s2, ch);
cout << " Appending " << ch << " results to " << s2 << endl;
ch = 'b';
append(s2, ch);
cout << " Appending " << ch << " results to " << s2 << endl;
//Test append function (appending a c-string to a c-string)
cout << endl;
cout << "Appending " << s1 << " to " << s2 << ", we get ";
append(s2, s1);
cout << s2 << endl;
can anyone deal this two append functions with C-string and without any built-in functions?
the ideal output will be following:
Given the c-string
Appending a results to a
Appending b results to ab
Appending massachussettes to ab, we get abmassachussettes
Explanation / Answer
#include <iostream>
using namespace std;
void append(char* &s,const char ch)
{
int i=0;
while(*(s+i)!='') //getting till the end of char array
{
i++;
}
*(s+i)=ch; //appending charater to last of array
*(s+i+1)=''; //terminating the character array
}
void append(char* &s1,const char* s2)
{
int i=0;
while(*(s1+i)!='') //getting till the end of char array s1
{
i++;
}
int j=0;
while(*(s2+j)!='') //getting till the end of char array s2
{
*(s1+i)=*(s2+j); //appending the character at index j of s2 to s1
j++;
i++;
}
*(s1+i+1)=''; //terminating the character array s1
}
int main() {
char str[]="massachussettes"; //storing the string in char array
char *s1=new char[15]; //dynamic allocation
s1=str;
char* s2 = new char[1]; //dynamiclly allocation
s2[0] = '';
cout << "Given the c-string " << s2 << endl;
char ch = 'a';
append(s2, ch);
cout << " Appending " << ch << " results to " << s2 << endl;
ch = 'b';
append(s2, ch);
cout << " Appending " << ch << " results to " << s2 << endl;
//Test append function (appending a c-string to a c-string)
cout << endl;
cout << "Appending " << s1 << " to " << s2 << ", we get ";
append(s2, s1);
cout << s2 << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.