implement few functions of cstring library

eXceed69 0 Tallied Votes 123 Views Share

This snippet shows different types of csting liblary implementation.

#include <iostream>
#include <cstring>
using namespace std;
 
 
//Function to find string length
int strLen(char*);
 
 
//Copies the second string to the first and also returns the first string after copy
char* strCpy(char*, char*);
 
 
//Concatenates the strings. The first string will now have concatenated string. It will also return the same.
char* strCat(char*, char*);
 
 
 
int strLen(char* str)
{
  //for loop to find the lenght of a string. '\0' used for identifying end of the string.
  int i;
  for (i=0; str[i]!='\0'; i++);
  return i;
}
 
 
char* strCpy(char* dest, char* src)
{
  
  int i;
  for (i=0; src[i]!='\0'; i++)
      dest[i] = src[i];
  dest[i] = '\0';
  return dest;
}
 
char* strCat(char* dest, char* src)
{
  
  int len, i, j;
  len = strLen(dest);
  for (i=len, j=0; src[j]!='\0'; i++, j++)
      dest[i] = src[j];
  dest[i] = '\0'; 
  return dest; 
}
 
int main()
{
 
    
    char * str1;
    char * str2;
    
    char s1[20];
    char s2[20];
    
    str1 = s1;
    str2 = s2;
 
    cout << "Please enter your 1st string : ";
    cin >> s1;
    cout << "Please enter your 2nd string : ";
    cin >> s2;
    
    cout << "\nThe length of " << str1 << " is " << strLen(str1) << ".\n";
    cout << "The length of " << str2 << " is " << strLen(str2) << ".\n";
    str1 = strCat(str1, str2);
    cout << "\nString Concatenation Result : " << str1 << "\n";
    str1 = strCpy(str1, str2);
    cout << "String Copy Result : " << str1 << "\n\n";
    system("pause");
    return 0;
}
ShawnCplus 456 Code Monkey Team Colleague

It is true '\0' means the end of a string but that is because it is the ASCII NULL code. A string can contain an '\0' before the actual end of the array though nothing after it will be seen when printing the string and there will be another NULL character at the end of the array.
In C++ char arrays this character is implied when creating an array.

Please correct me if I am wrong.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>> A string can contain an '\0' before the actual end of the array
Yes it can, but that makes it a binary string, not an ascii string, and most string functions in C and C++ will not be able to deal with it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.