<string>

Class string does not have conversion methods from int or char to string in a string definition.

Strings declared by class string:

  1. are not necessary null terminated (‘\0’).
  2. have a first subscript of 0 and last subscript of length – 1, where the length can be found from member function length().
  3. is not a pointer, therefore the expression &s[0] is not equivalent to s when s is a string.
  4. But for the third rule, we can declare a string pointer like string *ptr; to point at one object.

to_string(); convert numbers etc to string

cin >> astring; But can not read after space.

getline(cin,astring); read line from cin.

astring.lenth(); get the length of the string, “cat” is 3, cause no ‘\0’.

astring.at(i) is like atring[i], both of them start form 0, second one will not check to see if i in range.

stringa=stringb is like stringa.assign(stringb), the second one is from <string>.

stringa+=stringb is like stringa.append(stringb).

We can also compare two strings just using >,==,<,<=,>=,!=.

str.substr(pos, n) returns a new string made of characters from pos to pos+n, for example, str is 123456, pos is 0, n is 3, the result is 123.

str.compare(str2) if these two strings are equal, will return 0.

str.find(pattern, pos), it will try to find pattern from posth element. string a(“123456”); cout << a.find(“3456”,0); the answer is 2, means it found 3456 at the 2th position. Or it will return string::npos. You can also do this like string test = str.find(pattern)!=string::npos ? to_string(str.find(pattern)) : (“NOT FOUND!”);

str.erase(pos, n),Deletes n characters from str starting at pos

str.insert(pos, str2) Inserts a copy of str2 into str starting at pos.

str.replace(pos, n, str2) Replaces the n characters in str at pos with a copy of str2.

const char *cstr = str.c_str(); Convert string str to C-style char * type.

<cctype>

isalpha(ch) Returns true if ch is an alphabetic

isupper(ch), islower(ch), isdigit(ch)(‘0’-‘9’),isxdigit(ch) (‘0’ – ‘9’, ‘A’ – ‘F’, ‘a’ – ‘f’),

isspace(ch) Returns true if ch is a whitespace character.
These characters are ‘ ‘ (the space character), ‘\t’, ‘\n’, ‘\f’, ‘\v’, or ‘\r’, all of which appear as blank space.

toupper(ch) Returns ch converted to upper case (or ch itself if ch is not a letter).tolower(ch)

bool isDigitString(string str)
{
   if (str.length() == 0)
      return false;
   for (int i = 0; i < str.length(); i++)
   {
      if (!isdigit(str[i]))
         return false;
   }
   return true;
}
string toUpperCase(string str)
{
   string result = "";
   for (int i = 0; i < str.length(); i++)
   {
      result += toupper(str[i]);
   }
   return result;
}

Views: 155

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.