美文网首页
c++快速入门4:字符串

c++快速入门4:字符串

作者: python测试开发 | 来源:发表于2021-07-27 11:14 被阅读0次

本章演示如何操作C++文本字符串:字符数组的更简单、更强大的替代。

创建字符串变量

与char、int、float、double和bool数据类型不同,C++中没有原生的 "字符串 "数据类型--但是它的<string>库类提供了字符串对象,用来模拟字符串数据类型。为了使程序能够使用它,必须在程序开始时用#include <string>指令添加该库。

像<iostream>类库一样,<string>库也是std命名空间的一部分,它被C++标准库类所使用。这意味着字符串对象可以被称为std::string,或者在程序开始时包含using namespace std;指令时更简单地称为string。

字符串变量可以通过在变量名后面的圆括号中加入一个文本字符串来初始化。在C++中,文本字符串必须始终包含在""双引号字符中--''单引号只用于包围char数据类型的字符值。

与C语言程序员必须使用的char数组相比,C++字符串变量更容易操作,因为它可以自动调整大小以适应任何文本字符串的长度。在较低的层次上,文本仍然是作为字符数组存储的。
string.cpp

#include <string>
#include <iostream>
using namespace std ;

int main()
{
  string text = "9" ; // Declare and initialize.
  string term("9 ") ; // Alternative.
  string info = "Toys" ; // Declare and initialize.
  string color ; // Declare only.

  char hue[4] = {'R','e','d','\0' } ;
  color = hue ; // Assign char array.

  info = " Balloons" ; // Reassign.

  text += ( term + color + info ) ; // Build long string.

  cout << endl << text << endl ;

  return 0 ;
}

获取字符串输入

让用户输入带有空格的字符串时,例如句子,可以使用getline()函数。这个函数需要两个参数来指定字符串的来源和目的地。例如,其中cin函数是源,名为 "str "的字符串变量是目的地。
getline( cin , str ) 。
getline()函数从输入 "流 "中读出,直到遇到行末的换行符--当你点击Return时产生。
在混合使用cin和getline()函数时必须注意,因为getline()函数会自动读取输入缓冲区中的任何内容--给人以程序跳过一条指令的印象。cin.ignore()函数可以用来克服这个问题,它忽略了留在输入缓冲区的内容。

#include <string>
#include <iostream>
using namespace std ;

int main()
{
 string name ;

 cout << "Please enter your full name: ";
 cin >> name ;

 cout << "Welcome " << name << endl ;

 cout << "Please re-enter your full name: " ;

 // Uncomment the next line to correct this program.
 //cin.ignore( 256, '\n' );

 getline( cin, name ) ;

 cout << "Thanks, " << name << endl ;

 return 0 ;
}

cin.ignore()函数的参数指定它最多应丢弃256个字符,并在遇到换行符时停止。

字符串转换

convert.cpp


#include <string>
#include <sstream>
#include <iostream>
using namespace std ;

int main( )
{
  string term = "100" ; // String to convert to int.
  int number = 100 ; // Int to convert to string.
  string text ; // String variable for converted int.
  int num ; // Int variable for converted string
  stringstream stream ; // Intermediary stream object.

  // Convert string to int...
  stream << term ; // Load string into stream.
  stream >> num ; // Extract stream to int.
  num /= 4 ; // Manipulate the int.
  cout << "Integer value: " << num << endl ;
  cout << "Integer value: " << stoi(term) << endl ;

  // Reset the stream object back to new...
  stream.str("") ; // Reset the stream to an empty string.
  stream.clear() ; // Reset the stream bit flags (good,bad,eof,fail).

  // Convert int to string...
  stream << number ; // Load int into stream.
  stream >> text ; // Extract stream to string.
  text += " Per Cent" ; // Manipulate the string.
  cout << "String value: " << text << endl ;
  cout << "Integer value: " << to_string(number) << endl ;

  return 0 ;
}

符串的特性

C++ <string>库提供了许多函数,使我们可以轻松地处理字符串。
与char数组不同,字符串变量会动态放大以容纳分配给它的字符数,它当前的内存大小可以通过<string>库的capacity()函数来显示。一旦放大,分配的内存大小将保持不变,即使有更小的字符串被分配给该变量。

features.cpp


#include <string>
#include <iostream>
using namespace std ;

void computeFeatures( string ) ;

int main()
{
  string text = "C++ is fun" ;
  computeFeatures( text ) ;

  text += " for everyone" ;
  computeFeatures( text ) ;

  text = "C++ Fun" ;
  computeFeatures( text ) ;

  text.clear() ;
  computeFeatures( text ) ;

  return 0 ;
}

void computeFeatures( string text )
{
  cout << endl << "String: " << text << endl ;
  cout << "Size: " << text.size() ;
  cout << "    Capacity: " << text.capacity() ;
  cout << "    Empty?: " << text.empty() << endl ;
}

连接和比较字符串

当+运算符在赋值中用来连接字符串时,合并后的字符串被存储在字符串变量中。
<string>库的append()函数也可以用来连接字符串,在其括号内指定要附加的字符串值作为参数。

#include <string>
#include <iostream>
using namespace std ;



int main()
{
  string lang = "C++" ;
  string term = " Programming" ;
  string text = "C++ Programming" ;

  // Joining strings...
  cout << "Concatenated: " << ( lang + term ) << endl ; // Concatenates strings in output.
  cout << "Original: " << lang << endl ; // But does not change first variable.

  cout << "Appended: " << lang.append( term ) << endl ; // Appends second string in first variable.
  cout << "Original: " << lang << endl << endl ; // And does change first variable.

  // Comparing strings...
  cout << "Differ: " << ( lang == term ) << endl ; // 0 false.
  cout << "Match: " << ( lang == text ) << endl << endl ; // 1 true.


    cout << "Match: " << lang.compare( text ) << endl ; // 0 identical.
  cout << "Differ: " << lang.compare( term ) << endl ; // 1 string arg lower ascii code value.
  cout << "Lower ASCII: " << lang.compare( "zzzzz" ) << endl ; // -1 string arg higher ascii code value.

  return 0 ;
}

assign和swap

swap.cpp

#include <string>
#include <iostream>
using namespace std ;

int main()
{
  string front, back, text = "Always laugh when you can. It\'s cheap medicine." ;

  // Assignation...
  front.assign( text ) ; // Assign the full string.
  cout << endl << "Front: " << front << endl ;

  front.assign( text, 0, 27 ) ; // Assign elements 0 thru 27.
  cout << endl << "Front: " << front << endl ;

  back.assign ( text, 27 , text.size() ) ; // Assign elements 27 thru end.
  cout << "Back: " << back << endl ;
  
  // Swap...
  back.swap( front ) ; // Swap the full strings.
  cout << endl << "Front: " << front << endl ;
  cout << "Back: " << back << endl ;

  return 0 ;
}

查找子串

可以使用<string>库的find()函数来搜索字符串值,看它是否包含指定的 "子串"。
当搜索成功找到指定的子串时,find()函数会返回该子串的第一个字符在所搜索的字符串中第一次出现的索引号。当搜索失败时,find()返回一个值-1,表示失败。
在<string>库中还有几个函数与find()函数有关。其中两个是find_first_of()函数和find_first_not_of()函数。find_first_of()函数不是像find()函数那样寻找一个完整字符串的第一次出现,而是寻找指定字符串中任何一个字符的第一次出现,而find_first_not_of()则是寻找不在指定字符串中的字符的第一次出现。
find_last_of()和find_last_not_of()函数的工作方式类似--但是从字符串的末尾开始搜索,然后向前移动。

find.cpp

#include <string>
#include <iostream>
using namespace std ;

int main()
{
  string text = "I can resist anything but temptation." ;
  int num ;

  num = text.find( "resist" , 0 ) ;
  cout << "Position: " << num << endl ; 

  num = text.find( "nonsuch" , 0 ) ;
  cout << "Result: " << num << endl ;

  num = text.find_first_of( "If" ) ;
  cout << "First I: " << num << endl ;

  num = text.find_first_not_of( "If" ) ;
  cout << "First not I: " << num << endl ;

  num = text.find_last_of( "t" ) ;
  cout << "Last t: " << num << endl ;

  num = text.find_last_not_of( "t" ) ;
  cout << "Last not t: " << num << endl ;

  return 0 ;
}

替换子字符串

使用insert()函数可以将字符串插入另一个字符串中。
erase()函数从字符串中删除一个子串。
replace()函数巧妙地结合了erase()和insert()函数,既可以删除子串,又可以替换。
substr()函数可以从字符串中复制子串,它的第一个参数是它应该开始复制的索引位置,第二个参数是要复制的字符数。
at()函数复制字符串中任何指定位置的字符,该函数要求将索引位置作为其参数。

sub.cpp

#include <string>
#include <iostream>
using namespace std ;

int main()
{
  string text = "I do like the seaside" ;
  cout << "Original: " << text << endl ;

  text.insert( 10, "to be beside " ) ;
  cout << "Inserted: " << text << endl ;

  text.erase( 2, 3 ) ;
  cout << "Erased:  " << text << endl ;

  text.replace( 7, 25, "strolling by the sea" ) ;
  cout << "Replaced: " << text << endl ;
  cout << "Copied:  " << text.substr( 7, 9 ) << endl ;
  cout << "Last character: " << text.at( text.size() - 1 ) << endl ;

  return 0 ;
}

相关文章

网友评论

      本文标题:c++快速入门4:字符串

      本文链接:https://www.haomeiwen.com/subject/zrwwmltx.html