C++字符串的处理总结

说明:以下 的大部分内容摘自https://cplusplus.com/

简单补充

由于C++针对字符串提供了string类,相较于字符串数组,string更简单方便,因此C++处理字符或字符串重点是string类。这里简单总结一下通过cin来读取字符串到字符数组中。

(1)cin

#include <iostream>

using namespace std;

int main(void)
{
	char str[20];
	cin >> str;
	cout << str << endl;
	return 0;
}

最简单得一种输入方法,缺点是不能输入空格,输入空格会结束读取。

(2)cin.getline()

这个函数有两个参数,第一个是用来存储输入行的数组的名称,第二个参数是要读取的字符数(要包含’\0’)。

#include <iostream>

using namespace std;

int main(void)
{
	char str[20];
	cin.getline(str, 20);
	cout << str << endl;
	return 0;
}

(3)cin.get()

get()的参数和用法与getline()一致,需要注意的是get()不会丢弃换行符,换行符会留在输入序列中,在使用的时候特别要注意!!下面这个例子中,第10行的cin.get()不能少,它的作用是丢弃输入序列中的换行符,如果没有这一行,str2中不能存入字符。

#include <iostream>

using namespace std;

int main(void)
{
	char str1[20];
	char str2[20];
	cin.get(str1, 20);
	cin.get();
	cin.get(str2, 20);
	cout <<"str1:" << str1 << endl;
	cout << "str2:" << str2 << endl;
	return 0;
}

1.input

(1).cin

这种方法遇到空格制表符回车就会终止读取,有时候也可以利用这个特点来读取多个单词。

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string str;
	cin >> str;
	cout << str << endl;
	return 0;
}

(2).getline

注意与cin.getline()的区别,cin.getline()是输入流对象的成员函数,getline()是string类的成员函数,在读取字符串到string用getline().

getline()函数由如下四种重载形式:

istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

is :表示一个输入流,例如 cin。
str :string类型的引用,用来存储输入流中的流信息。
delim :char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到’\n’,则终止输入

示例1:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string str;
	getline(cin, str);
	cout << str << endl;
	return 0;
}

示例2:对输入的IP地址进行分割

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string str1, str2, str3, str4;
	getline(cin, str1,'.');
	getline(cin, str2, '.');
	getline(cin, str3, '.');
	getline(cin, str4);
	cout << str1 << endl;
	cout << str2 << endl;
	cout << str3 << endl;
	cout << str4 << endl;
	return 0;
}

输入:192.168.1.100

输出:
192 168 1 100

2.Modifiers

(1). operator =

这是最简单,最常用的赋值方式。

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string str;
	str = "Hello World!";
	cout << str << endl;
	return 0;
}

(2).operator+=

string& operator+= (const string& str);
string& operator+= (const char* s);
string& operator+= (char c);

示例:

// string::operator+=
#include <iostream>
#include <string>

int main()
{
	std::string name("John");
	std::string family("Smith");
	name += " K. ";         // c-string
	name += family;         // string
	name += '\n';           // character

	std::cout << name;
	return 0;
}

输出:John K. Smith

(3) operator +

string (1)string operator+ (const string& lhs, const string& rhs);
c-string (2)string operator+ (const string& lhs, const char* rhs); string operator+ (const char* lhs, const string& rhs);
character (3)string operator+ (const string& lhs, char rhs); string operator+ (char lhs, const string& rhs);

Example

// concatenating strings
#include <iostream>
#include <string>

int main()
{
	std::string firstlevel("com");
	std::string secondlevel("cplusplus");
	std::string scheme("http://");
	std::string hostname;
	std::string url;

	hostname = "www." + secondlevel + '.' + firstlevel;
	url = scheme + hostname;

	std::cout << url << '\n';

	return 0;
}

Output:

http://www.cplusplus.com 

(4).insert

string (1)string& insert (size_t pos, const string& str);
substring (2)string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
c-string (3)string& insert (size_t pos, const char* s);
buffer (4)string& insert (size_t pos, const char* s, size_t n);
fill (5)string& insert (size_t pos, size_t n, char c); void insert (iterator p, size_t n, char c);
single character (6)iterator insert (iterator p, char c);
range (7)template <class InputIterator> void insert (iterator p, InputIterator first, InputIterator last);

Example

// inserting into a string
#include <iostream>
#include <string>

int main ()
{
  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )

  std::cout << str << '\n';
  return 0;
}

(5).erase

sequence (1)string& erase (size_t pos = 0, size_t len = npos);
character (2)iterator erase (iterator p);
range (3) iterator erase (iterator first, iterator last);

Example

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

int main()
{
    std::string str("This is an example sentence.");
    std::cout << str << '\n';
    // "This is an example sentence."
    str.erase(10, 8);                        //            ^^^^^^^^
    std::cout << str << '\n';
    // "This is an sentence."
    str.erase(str.begin() + 9);               //           ^
    std::cout << str << '\n';
    // "This is a sentence."
    str.erase(str.begin() + 5, str.end() - 9);  //       ^^^^^
    std::cout << str << '\n';
    // "This sentence."
    return 0;
}

(6).replace

string (1)string& replace (size_t pos, size_t len, const string& str); string& replace (iterator i1, iterator i2, const string& str);
substring (2)string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
c-string (3)string& replace (size_t pos, size_t len, const char* s); string& replace (iterator i1, iterator i2, const char* s);
buffer (4)string& replace (size_t pos, size_t len, const char* s, size_t n); string& replace (iterator i1, iterator i2, const char* s, size_t n);
fill (5)string& replace (size_t pos, size_t len, size_t n, char c); string& replace (iterator i1, iterator i2, size_t n, char c);
range (6)template <class InputIterator> string& replace (iterator i1, iterator i2, InputIterator first, InputIterator last);

Example

// replacing in a string
#include <iostream>
#include <string>

int main()
{
	std::string base = "this is a test string.";
	std::string str2 = "n example";
	std::string str3 = "sample phrase";
	std::string str4 = "useful.";

	// replace signatures used in the same order as described above:

	// Using positions:                 0123456789*123456789*12345
	std::string str = base;           // "this is a test string."
	str.replace(9, 5, str2);          // "this is an example string." (1)
	str.replace(19, 6, str3, 7, 6);     // "this is an example phrase." (2)
	str.replace(8, 10, "just a");     // "this is just a phrase."     (3)
	str.replace(8, 6, "a shorty", 7);  // "this is a short phrase."    (4)
	str.replace(22, 1, 3, '!');        // "this is a short phrase!!!"  (5)

	// Using iterators:                                               0123456789*123456789*
	str.replace(str.begin(), str.end() - 3, str3);                    // "sample phrase!!!"      (1)
	str.replace(str.begin(), str.begin() + 6, "replace");             // "replace phrase!!!"     (3)
	str.replace(str.begin() + 8, str.begin() + 14, "is coolness", 7);    // "replace is cool!!!"    (4)
	str.replace(str.begin() + 12, str.end() - 4, 4, 'o');                // "replace is cooool!!!"  (5)
	str.replace(str.begin() + 11, str.end(), str4.begin(), str4.end());// "replace is useful."    (6)
	std::cout << str << '\n';
	return 0;
}

(7).swap

void swap (string& str);

Example

// swap strings
#include <iostream>
#include <string>

int main()
{
	std::string buyer("money");
	std::string seller("goods");

	std::cout << "Before the swap, buyer has " << buyer;
	std::cout << " and seller has " << seller << '\n';

	seller.swap(buyer);

	std::cout << " After the swap, buyer has " << buyer;
	std::cout << " and seller has " << seller << '\n';

	return 0;
}

3.Element access

(1).operator[]

char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
// string::operator[]
#include <iostream>
#include <string>

int main()
{
    std::string str("Test string");
    for (int i = 0; i < str.length(); ++i)
    {
        std::cout << str[i];
    }
    return 0;
}

(2).at

char& at (size_t pos);
const char& at (size_t pos) const;
// string::at
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}

(3).front

char& front();
const char& front() const;
// string::front
#include <iostream>
#include <string>

int main ()
{
  std::string str ("test string");
  str.front() = 'T';
  std::cout << str << '\n';
  return 0;
}

(4)back

   char& back();
const char& back() const;
// string::back
#include <iostream>
#include <string>

int main ()
{
  std::string str ("hello world.");
  str.back() = '!';
  std::cout << str << '\n';
  return 0;
}

4.Capacity

(1).size

size_t size() const;
// string::size
#include <iostream>
#include <string>

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

(2).length

size_t length() const;
// string::length
#include <iostream>
#include <string>

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

(3).clear

void clear();
// 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;
}

(4).empty

bool empty() const;
// 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;
}

5.Iterators

(1).begin & end

      iterator begin();
const_iterator begin() const;

 iterator end();
const_iterator end() const;
// string::begin/end
#include <iostream>
#include <string>

int main()
{
    std::string str("Test string");
    for (std::string::iterator it = str.begin(); it != str.end(); ++it)
        std::cout << *it;
    std::cout << '\n';

    return 0;
}

(2).rbegin & rend

 reverse_iterator rbegin();
const_reverse_iterator rbegin() const;

reverse_iterator rend();
const_reverse_iterator rend() const;
// string::rbegin/rend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("now step live...");
  for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
    std::cout << *rit;
  return 0;
}

6.String operations

(1).c_str

c_str部分摘自http://t.csdn.cn/xk1oP

const char* c_str() const;

c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同。这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。

注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针。

错误用法:

 char* c;
string s="1234";
c = s.c_str();

正确用法:

char c[20];
string s="1234";
strcpy(c,s.c_str());

Example

#include <iostream>
#include <cstring>
#include <string>

int main()
{
    std::string str("Please split this sentence into tokens");

    //重点是下面的两行
    char* cstr = new char[str.length() + 1];
    std::strcpy(cstr, str.c_str());

    // cstr now contains a c-string copy of str

    char* p = std::strtok(cstr, " ");
    while (p != 0)
    {
        std::cout << p << '\n';
        p = std::strtok(NULL, " ");
    }

    delete[] cstr;
    return 0;
}

(2).copy

Copy sequence of characters from string

size_t copy (char* s, size_t len, size_t pos = 0) const;
// string::copy
#include <iostream>
#include <string>

int main ()
{
  char buffer[20];
  std::string str ("Test string...");
  std::size_t length = str.copy(buffer,6,5);
  buffer[length]='\0';
  std::cout << "buffer contains: " << buffer << '\n';
  return 0;
}

(3).find

Searches the string for the first occurrence of the sequence specified by its arguments.

When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences that include characters before pos.

Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match.

string (1)size_t find (const string& str, size_t pos = 0) const;
c-string (2)size_t find (const char* s, size_t pos = 0) const;
buffer (3)size_t find (const char* s, size_t pos, size_t n) const;
character (4)size_t find (char c, size_t pos = 0) const;
Parametresdescription
strAnother string with the subject to search for.
posPosition of the first character in the string to be considered in the search.
If this is greater than the string length, the function never finds matches.
Note: The first character is denoted by a value of 0 (not 1): A value of 0 means that the entire string is searched.
sPointer to an array of characters.
If argument n is specified (3), the sequence to match are the first n characters in the array.
Otherwise (2), a null-terminated sequence is expected: the length of the sequence to match is determined by the first occurrence of a null character.
nLength of sequence of characters to match.
cIndividual character to be searched for.
// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main()
{
    std::string str("There are two needles in this haystack with needles.");
    std::string str2("needle");

    // different member versions of find in the same order as above:
    std::size_t found = str.find(str2);
    if (found != std::string::npos)
        std::cout << "first 'needle' found at: " << found << '\n';

    found = str.find("needles are small", found + 1, 6);
    if (found != std::string::npos)
        std::cout << "second 'needle' found at: " << found << '\n';

    found = str.find("haystack");
    if (found != std::string::npos)
        std::cout << "'haystack' also found at: " << found << '\n';

    found = str.find('.');
    if (found != std::string::npos)
        std::cout << "Period found at: " << found << '\n';

    // let's replace the first needle:
    str.replace(str.find(str2), str2.length(), "preposition");
    std::cout << str << '\n';

    return 0;
}

(4).rfind

string (1)size_t rfind (const string& str, size_t pos = npos) const;
c-string (2)size_t rfind (const char* s, size_t pos = npos) const;
buffer (3)size_t rfind (const char* s, size_t pos, size_t n) const;
character (4)size_t rfind (char c, size_t pos = npos) const;
// string::rfind
#include <iostream>
#include <string>
#include <cstddef>

int main()
{
    std::string str("The sixth sick sheik's sixth sheep's sick.");
    std::string key("sixth");

    std::size_t found = str.rfind(key);
    if (found != std::string::npos)
        str.replace(found, key.length(), "seventh");

    std::cout << str << '\n';

    return 0;
}

(5).find_first_of

Searches the string for the first character that matches any of the characters specified in its arguments.

string (1)size_t find_first_of (const string& str, size_t pos = 0) const;
c-string (2)size_t find_first_of (const char* s, size_t pos = 0) const;
buffer (3)size_t find_first_of (const char* s, size_t pos, size_t n) const;
character (4)size_t find_first_of (char c, size_t pos = 0) const;
// string::find_first_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, replace the vowels in this sentence by asterisks.");
  std::size_t found = str.find_first_of("aeiou");
  while (found!=std::string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

  std::cout << str << '\n';

  return 0;
}

(6).find_last_of

Searches the string for the last character that matches any of the characters specified in its arguments.

string (1)size_t find_last_of (const string& str, size_t pos = npos) const;
c-string (2)size_t find_last_of (const char* s, size_t pos = npos) const;
buffer (3)size_t find_last_of (const char* s, size_t pos, size_t n) const;
character (4)size_t find_last_of (char c, size_t pos = npos) const;
// string::find_last_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>         // std::size_t

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::size_t found = str.find_last_of("/\\");
  std::cout << " path: " << str.substr(0,found) << '\n';
  std::cout << " file: " << str.substr(found+1) << '\n';
}

int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}

(7).find_first_not_of

Searches the string for the first character that does not match any of the characters specified in its arguments.

When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences before that character.

string (1)	
size_t find_first_not_of (const string& str, size_t pos = 0) const;
c-string (2)	
size_t find_first_not_of (const char* s, size_t pos = 0) const;
buffer (3)	
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
character (4)	
size_t find_first_not_of (char c, size_t pos = 0) const;
// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main()
{
    std::string str("look for non-alphabetic characters...");

    std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");

    if (found != std::string::npos)
    {
        std::cout << "The first non-alphabetic character is " << str[found];
        std::cout << " at position " << found << '\n';
    }

    return 0;
}

(7).find_last_not_of

Searches the string for the last character that does not match any of the characters specified in its arguments.

When pos is specified, the search only includes characters at or before position pos, ignoring any possible occurrences after pos.

string (1)size_t find_last_not_of (const string& str, size_t pos = npos) const;
c-string (2)size_t find_last_not_of (const char* s, size_t pos = npos) const;
buffer (3)size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
character (4)size_t find_last_not_of (char c, size_t pos = npos) const;
// string::find_last_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main()
{
    std::string str("Please, erase trailing white-spaces   \n");
    std::string whitespaces(" \t\f\v\n\r");

    std::size_t found = str.find_last_not_of(whitespaces);
    if (found != std::string::npos)
        str.erase(found + 1);
    else
        str.clear();            // str is all whitespace

    std::cout << '[' << str << "]\n";

    return 0;
}

(8).substr

string substr (size_t pos = 0, size_t len = npos) const;
// string::substr
#include <iostream>
#include <string>

int main()
{
    std::string str = "We think in generalities, but we live in details.";
    // (quoting Alfred N. Whitehead)

    std::string str2 = str.substr(3, 5);     // "think"

    std::size_t pos = str.find("live");      // position of "live" in str

    std::string str3 = str.substr(pos);     // get from "live" to the end

    std::cout << str2 << ' ' << str3 << '\n';

    return 0;
}

(9).compare

Compares the value of the string object (or a substring) to the sequence of characters specified by its arguments.

The compared string is the value of the string object or -if the signature used has a pos and a len parameters- the substring that begins at its character in position pos and spans len characters.

This string is compared to a comparing string, which is determined by the other arguments passed to the function.

string (1)int compare (const string& str) const;
substrings (2)int compare (size_t pos, size_t len, const string& str) const; int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
c-string (3)int compare (const char* s) const; int compare (size_t pos, size_t len, const char* s) const;
buffer (4)int compare (size_t pos, size_t len, const char* s, size_t n) const;

Return Value

valuerelation between compared string and comparing string
0They compare equal
<0Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
>0Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
// comparing apples with apples
#include <iostream>
#include <string>

int main()
{
    std::string str1("green apple");
    std::string str2("red apple");

    if (str1.compare(str2) != 0)
        std::cout << str1 << " is not " << str2 << '\n';

    if (str1.compare(6, 5, "apple") == 0)
        std::cout << "still, " << str1 << " is an apple\n";

    if (str2.compare(str2.size() - 5, 5, "apple") == 0)
        std::cout << "and " << str2 << " is also an apple\n";

    if (str1.compare(6, 5, str2, 4, 5) == 0)
        std::cout << "therefore, both are apples\n";

    return 0;
}

7.Convert from strings

(1).stoi

Parses str interpreting its content as an integral number of the specified base, which is returned as an int value.

If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number.

The function uses strtol (or wcstol to perform the conversion (see strtol for more details on the process).

int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

Parameters

  • str:String object with the representation of an integral number.
  • idx:Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used.
  • base:Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence (see strtol for details). Notice that by default this argument is 10, not 0.
// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main(void)
{
	std::string str_dec = "2001, A Space Odyssey";
	std::string str_hex = "40c3";
	std::string str_bin = "-10010110001";
	std::string str_auto = "0x7f";

	std::string::size_type sz;   // alias of size_t

	int i_dec = std::stoi(str_dec, &sz);
	int i_hex = std::stoi(str_hex, nullptr, 16);
	int i_bin = std::stoi(str_bin, nullptr, 2);
	int i_auto = std::stoi(str_auto, nullptr, 0);

	std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
	std::cout << str_hex << ": " << i_hex << '\n';
	std::cout << str_bin << ": " << i_bin << '\n';
	std::cout << str_auto << ": " << i_auto << '\n';

	return 0;
}

(2).stol

long stol (const string&  str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);
// stol example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stol

int main()
{
	std::string str_dec = "1987520";
	std::string str_hex = "2f04e009";
	std::string str_bin = "-11101001100100111010";
	std::string str_auto = "0x7fffff";

	std::string::size_type sz;   // alias of size_t

	long li_dec = std::stol(str_dec, &sz);
	long li_hex = std::stol(str_hex, nullptr, 16);
	long li_bin = std::stol(str_bin, nullptr, 2);
	long li_auto = std::stol(str_auto, nullptr, 0);

	std::cout << str_dec << ": " << li_dec << '\n';
	std::cout << str_hex << ": " << li_hex << '\n';
	std::cout << str_bin << ": " << li_bin << '\n';
	std::cout << str_auto << ": " << li_auto << '\n';

	return 0;
}

(3).stoul

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);
unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);
// stoul example
#include <iostream>   // std::cin, std::cout
#include <string>     // std::string, std::stoul, std::getline

int main ()
{
  std::string str;
  std::cout << "Enter an unsigned number: ";
  std::getline (std::cin,str);
  unsigned long ul = std::stoul (str,nullptr,0);
  std::cout << "You entered: " << ul << '\n';
  return 0;
}

(4).stoll

long long stoll (const string&  str, size_t* idx = 0, int base = 10);
long long stoll (const wstring& str, size_t* idx = 0, int base = 10);
// stoll example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoll

int main ()
{
  std::string str = "8246821 0xffff 020";

  std::string::size_type sz = 0;   // alias of size_t

  while (!str.empty()) {
    long long ll = std::stoll (str,&sz,0);
    std::cout << str.substr(0,sz) << " interpreted as " << ll << '\n';
    str = str.substr(sz);
  }

  return 0;
}

(5).stoul

unsigned long long stoull (const string&  str, size_t* idx = 0, int base = 10);
unsigned long long stoull (const wstring& str, size_t* idx = 0, int base = 10);
// stoull example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoull

int main ()
{
  std::string str = "8246821 0xffff 020 -1";

  std::string::size_type sz = 0;   // alias of size_t

  while (!str.empty()) {
    unsigned long long ull = std::stoull (str,&sz,0);
    std::cout << str.substr(0,sz) << " interpreted as " << ull << '\n';
    str = str.substr(sz);
  }

  return 0;
}

(6).stof

float stof (const string&  str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);
// stof example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stof

int main ()
{
  std::string orbits ("686.97 365.24");
  std::string::size_type sz;     // alias of size_t

  float mars = std::stof (orbits,&sz);
  float earth = std::stof (orbits.substr(sz));
  std::cout << "One martian year takes " << (mars/earth) << " Earth years.\n";
  return 0;
}

(7).stod

double stod (const string&  str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
// stod example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stod

int main ()
{
  std::string orbits ("365.24 29.53");
  std::string::size_type sz;     // alias of size_t

  double earth = std::stod (orbits,&sz);
  double moon = std::stod (orbits.substr(sz));
  std::cout << "The moon completes " << (earth/moon) << " orbits per Earth year.\n";
  return 0;
}

(8).stold

long double stold (const string&  str, size_t* idx = 0);
long double stold (const wstring& str, size_t* idx = 0);
// stold example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stod

int main ()
{
  std::string orbits ("90613.305 365.24");
  std::string::size_type sz;     // alias of size_t

  long double pluto = std::stod (orbits,&sz);
  long double earth = std::stod (orbits.substr(sz));
  std::cout << "Pluto takes " << (pluto/earth) << " years to complete an orbit.\n";
  return 0;
}

8.Convert to strings

to_string

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
  std::string pi = "pi is " + std::to_string(3.1415926);
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << pi << '\n';
  std::cout << perfect << '\n';
  return 0;
}

9.string 分割

string类并没有提供对string字符串进行分割的函数,需要自己实现,以下的几种方法中方法四较为通用且实现也很简单。

  • 方法一:find() + substr()

    #include<iostream>
    #include<vector>
    #include <string>
    
    using namespace std;
    
    
    int main()
    {
    	rsize_t pos=-1,begin=-1,end=-1;
    	string temp;
    	vector<string> vec;
    	string str = "192.168.1.100";
    	do
    	{
    		pos = str.find( '.',pos+1);
    		begin = end+1;
    		end = pos;
    		temp = str.substr(begin, end - begin);
    		vec.push_back(temp);
    		
    
    	} while (pos != string::npos);
    	/*for (vector<string>::iterator i = vec.begin(); i != vec.end(); i++)
    	{
    		cout << *i << endl;
    	}*/
    	for (int i = 0; i < vec.size(); i++)
    		cout << vec.at(i) << endl;
    }
    
    • 方法二:getline()

    用getline()函数可以对 cin 输入的字符串进行分割,此时的函数原型为:istream& getline (istream& is, string& str)

    #include<iostream>
    #include<vector>
    #include <string>
    
    using namespace std;
    
    
    int main(void)
    {
    	string str;
    	vector<string> vec;
    	while (getline(cin,str, '.'))
    	{
    		vec.push_back(str);
    	}
    	for (int i = 0; i < vec.size(); i++)
    		cout << vec.at(i) << endl;
    }
    
    • 方法三:stringstream类,这种方法只能用于以空格或tab键进行分割。
    #include<iostream>
    #include<vector>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    
    int main(void)
    {
    	string str;
    	vector<string> vec;
    	stringstream ss;
    	getline(cin, str);
    	ss << str;
    	while (ss >> str)
    	{
    		vec.push_back(str);
    	}
    	for (int i = 0; i < vec.size(); i++)
    		cout << vec.at(i) << endl;
    }
    

    输入:This is a test!

    输出:

    This is a test!

  • 方法四:getline()+stringstream类,这种方法可以实现以任一字符进行分割,且实现也较简单,在具体应用的时候可以将其封装成一个函数。

    #include<iostream>
    #include<vector>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main(void)
    {
    	string str = "192.168.1.100";  //要分割的字符串
    	vector<string> vec;   //保存分割结果
    	stringstream ss(str); //string流
    	ss << str;  
    	while (getline(ss,str,'.'))
    	{
    		vec.push_back(str);
    	}
    	for (int i = 0; i < vec.size(); i++)
    		cout << vec.at(i) << endl;
    }
    

    将其封装成函数:

    /*
    str --- 要分割的字符串
    ch --- 分隔符
    vec --- 保存分割结果
    */
    void stringSplit(const string str, const char ch, vector<string>& vec)
    {
    	string temp;
    	stringstream ss(str);
    	while (getline(ss, temp, ch))
    	{
    		vec.push_back(temp);
    	}
    }
    

    10.reverse 字符串反转

    #include<iostream>
    #include<vector>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main(void)
    {
    	string str = "192.168.1.100";  
    	reverse(str.begin(), str.end());
    	cout << str << endl;
    }
    

    输出:001.1.861.291

11.大小写转换

#include<iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(void)
{
	string str1 = "ABCabc";
	string str2 = str1;
	transform(str1.begin(), str1.end(), str2.begin(), toupper);
	cout << "转大写:" << str2 << endl;
	transform(str1.begin(), str1.end(), str2.begin(), tolower);
	cout << "转小写:" << str2 << endl;

}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忆昔z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值