Use strcpy(), strcat(), strcmp(), and strlen() for basic null-terminated string functions. - C++ Data Type

C++ examples for Data Type:char array

Description

Use strcpy(), strcat(), strcmp(), and strlen() for basic null-terminated string functions.

Demo Code

#include <iostream>
#include <cstring>
using namespace std;
int main() {/*w  w  w. j  a v a 2s  .c  o m*/
   char strA[7] = "Up";
   char strB[5] = "Down";
   char strC[5] = "Left";
   char strD[6] = "Right";
   cout << "Here are the strings: " << endl;
   cout << "strA: " << strA << endl;
   cout << "strB: " << strB << endl;
   cout << "strC: " << strC << endl;
   cout << "strD: " << strD << "\n\n";
   // Display the length of strA.
   cout << "Length of strA is " << strlen(strA) << endl;
   // Concatenate strB with strA.
   strcat(strA, strB);
   cout << "strA after concatenation: " << strA << endl;
   cout << "Length of strA is now " << strlen(strA) << endl;
   // Copy strC into strB.
   strcpy(strB, strC);
   cout << "strB now holds: " << strB << endl;
   // Compare strings.
   if(!strcmp(strB, strC))
      cout << "strB is equal to strC\n";
   int result = strcmp(strC, strD);
   if(!result)
      cout << "strC is equal to strD\n";
   else if(result < 0)
   cout << "strC is less than strD\n";
   else if(result > 0)
   cout << "strC is greater than strD\n";
   return 0;
}

Result


Related Tutorials