Write these cString functions in C++ without using Cstring library. StrLen (of a
ID: 3684138 • Letter: W
Question
Write these cString functions in C++ without using Cstring library.
StrLen(of a cstring)
StrCpy(destination cstring, source cstring)
StrCat(destination cstring, source cstring)
SubStr(source cstring, start pos, length, sub cstring);
StrCmp(this cstring, that cstring) //returns 1, 0, or -1 (see description of strcmp)
StrChr(cstring, character) //return the index of character in cstring
StrRChr(cstring, character) //search in reverse for character in cstring
StrNCpy( destination cstring, source cstring, num of characters to copy)
StrNCat( destination cstring, source cstring, num of characters to concatenate)
StrNCmp(this string, that string, n: max characters to compare) //compare at most n characters
Explanation / Answer
1.
int StrLen(char[],s)
{
int i,length=0;
for(i=0;s[i]!='';i++)
{
length++;
}
return length;
}
2.
void StrCpy(char s1[])
{
char s2[20];
int i;
for(i=0;s1[i]!='';i++)
s2[i]=s1[i];
s2[--i]='';
}
3.
void StrCat(char s1[], char s2[])
{
int i, j;
i = 0;
while (s1[i] != '')
{ //to append atthe end of s1
i++;
}
j= 0;
while (s2[j] != '')
{
s1[i] = s2[j];
j++;
i++;
}
s1[i] = '';
}
4.
void SubStr(char source[], char sub[], int pos, int len)
{
int i= 0;
while (i<len)
{
sub[i] = source[pos+i-1];
i++;
}
sub[i] = '';
}
5.
int compare_strings(char s1[], char s2[])
{
int i = 0;
while (s1[i] == s2[i])
{
if (s1[i] == '' || s2[i] == '')
break;
i++;
}
if (s1[i] == '' && s2[i] == '')
return 0;
else
if(s2[i]==''||s1[i]>s2[i])
return 1;
else
return -1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.