C++ string length

Description

C++ string length

#include <iostream>
#include <string>
using namespace std;
int main()//ww w  . jav a  2  s . c o  m
{
   char charray[80];
   string word;
   cout << "Enter a word: ";
   cin >> word;
   int wlen = word.length();     //length of string object
   cout << "One character at a time: ";
   for(int j=0; j<wlen; j++)
      cout << word.at(j);        //exception if out-of-bounds
   //    cout << word[j];           //no warning if out-of-bounds
   word.copy(charray, wlen, 0);  //copy string object to array
   charray[wlen] = 0;            //terminate with '\0'
   cout << "\nArray contains: " << charray << endl;
   return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()/*from   www.  j a va  2  s. co  m*/
{
   string string1 = "Hello";
   string string2 = "Hello there";
   cout << "string1 is the string: " << string1 << endl;
   cout << "The number of characters in string1 is " << int(string1.length()) << endl << endl;
   cout << "string2 is the string: " << string2 << endl;
   cout << "The number of characters in string2 is " << int(string2.length()) << endl << endl;
   
   if (string1 < string2)
      cout << string1 << " is less than " << string2 << endl << endl;
   else if (string1 == string2)
      cout << string1 << " is equal to " << string2 << endl << endl;
   else
      cout << string1 << " is greater than " << string2 << endl << endl;
   string1 = string1 + " there world!";
   cout << "After concatenation, string1 contains the characters: " << string1 << endl;
   cout << "The length of this string is " << int(string1.length()) << endl;
   return 0;
}



PreviousNext

Related