string常用成员函数

string常用成员函数

std::string::clear

Clear string

Erases the contents of the string, which becomes an empty string (with a length of 0 characters).

Parameters

none

Return value

none

Example

// string::clear
#include <iostream>
#include <string>

int main ()
{
  char c;
  std::string str;
  std::cout << "Please type some lines of text. Enter a dot (.) to finish:\n";
  do {
    c = std::cin.get();
    str += c;
    if (c=='\n')
    {
       std::cout << str;
       str.clear();
    }
  } while (c!='.');
  return 0;
}

This program repeats every line introduced by the user until a line contains a dot ('.'). Every newline character ('\n') triggers(触发) the repetition of the line and the clearing of the current string content.

const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
c_str函数的返回值是const char *,不能直接赋值给char *

compare用于比较两个字符串是否相等。
用法:
str1.compare(str2);
str1=str2,输出0;
str1>str2,输出>0;
str1<str2,输出<0。

std::string::empty

Test if string is empty

Returns whether the string is empty (i.e. whether its length is 0).
This function does not modify the value of the string in any way. To clear the content of a string, see string::clear.

Parameters

none

Return Value

true if the string length is 0, false otherwise.

Example

// string::empty
#include <iostream>
#include <string>

int main ()
{
  std::string content;
  std::string line;
  std::cout << "Please introduce a text. Enter an empty line to finish:\n";
  do {
    getline(std::cin,line);
    content += line + '\n';
  } while (!line.empty());
  std::cout << "The text you introduced was:\n" << content;
  return 0;
}

This program reads the user input line by line and stores it into string content until an empty line is introduced.

std::string::length/size

Return length of string

Returns the length of the string, in terms of bytes.
This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity(存储容量).
Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).
Both string::size and string::length are synonyms and return the exact same value.

Parameters

none

Return Value

The number of bytes in the string.
size_t is an unsigned integral type (the same as member type string::size_type).

Example

// string::length/size
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " bytes.\n";
//std::cout << "The size of str is " << str.size() << " bytes.\n";
  return 0;
}

Output:
The size of str is 11 bytes

posted @ 2019-07-16 19:58  文成宇  阅读(564)  评论(0编辑  收藏  举报