Write a C++ function named stringCopy that takes two C-strings s1 and s2 and cop
ID: 3915195 • Letter: W
Question
Write a C++ function named stringCopy that takes two C-strings s1 and s2 and copies the characters of s1 to s2. Note that when we call this function from the main program, both S1 and S2 are created such that the null character is placed at the end of both of them. For this reason, inside this function it is easy to compute the length of S1 and S2 using stringLength function given in question #1 to find lengths. The copying of characters of S1 to S2 must follow the following rules: Rule 1: If the length of S1 and S2 are equal, then copy all the characters of S1 to S2. Rule 2: If the length of S2 is smaller than length of S1 then S2 does not have enough space to copy all the characters of S1. Therefore this function should NOT copy any character of S1 to S2 and must return without doing anything. Rule 3: If the length of S2 is greater than length of S1 then copy all the characters of S1 to S2 and put a null character next to the last character copied. Therefore in this case S2 will have two null characters: one at the end of it which was put in the main program and another next to the last character copied which is put in this function. The main program to test the stringCopy function is given below
Explanation / Answer
#include<iostream>
using namespace std;
//function that returns the length of the string
int stringLength(char a[])
{
int i=0;
while(a[i]!='')i++;//counting upto null character
return i;//returning length
}
//method to copy string s1 to s2
void stringCopy(char s1[],char s2[])
{
int n1 = stringLength(s1);//finding length of s1
int n2 = stringLength(s2);//finding length of s2
//#rule 1 both lengths are equal
if(n1 == n2)
{//then copying all characters in s1 to s2
int i=0;
while(i<n1)
{
s2[i]=s1[i];//copying characters in s1 to s2
i++;
}
}
else if(n1<n2)//rule4 if length of s2> length of s1
{
//then copy all the characters of S1 to S2 and put a null character next to the last character copied
int i=0;
while(i<n1)
{
s2[i]=s1[i];//copying characters in s1 to s2
i++;
}
//setting next character to null
s2[i]='';
}
else//rule2....if n1>n2
{
//do nothing......
}
}
//testing method
int main()
{
char s1[100],s2[100];
int i=0;
while(i<3)
{
cout<<"Enter string1:";
cin>>s1;
cout<<"Enter string2:";
cin>>s2;
stringCopy(s1,s2);
cout<<"String after copy: string1:"<<s1<<" string2:"<<s2<<endl;
i++;
}
return 0;
}
output:
Enter string1:hello
Enter string2:world
String after copy: string1:hello string2:hello
Enter string1:hx
Enter string2:world
String after copy: string1:hx string2:hx
Enter string1:hello
Enter string2:wor
String after copy: string1:hello string2:wor
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.