现在的位置: 首页 > 综合 > 正文

C++ 标准模板库学习之 string 类 详解 (一) 将一个句子中每个单词的单词字母顺序翻转 关于npos find_first_not_of find_first_of getline

2013年03月07日 ⁄ 综合 ⁄ 共 6626字 ⁄ 字号 评论关闭

先看例子程序:

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

void test_getline(void)
{
   string s1;
   cout << "Enter a sentence (use <space> as the delimiter): "<<endl;
   getline(cin,s1, ' ');
   cout << "You entered: " << s1 << endl;
   cout << "Enter a sentence (use <Enter> as the delimiter): "<<endl;
   getline(cin,s1, '\n');
   cout << "You entered: " << s1 << endl;;
}
/***************
运行结果:
Enter a sentence (use <space> as the delimiter):
think out of the box
You entered: think
Enter a sentence (use <Enter> as the delimiter):
You entered: out of the box
****************/
void test_find_first_of(void)
{
    string str ("Replace the vowels in this sentence by asterisks.");
    size_t found;

    found=str.find_first_of("aeiou");
    while (found!=string::npos)
    {
        str[found]='*';
        found=str.find_first_of("aeiou",found+1);
    }
    cout << str << endl;
}
/***************
运行结果:
R*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
****************/
void  test_find_first_not_of(void)
{
    string str("look for non-alphabetic characters...");
    size_t found;
    found=str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
    if (found!=string::npos)
    {
        cout << "First non-alphabetic character is " << str[found];
        cout << " at position " << int(found) << endl;
    }
}
/***************
运行结果:
First non-alphabetic character is - at position 12
****************/
int main (int argc, char** argv)
{
   test_getline();
   cout<<endl<<"******************************************"<<endl;
   test_find_first_of();
   cout<<endl<<"******************************************"<<endl;
   test_find_first_not_of();
   cout<<endl<<"******************************************"<<endl;
   const string delims(" \t,.;");
   string line;
   cout<<"\nplease input a sentence :\n";
   // for every line read successfully
   while (getline(cin,line))
   {
       cout<<"\nafter reverse:\n";
       string::size_type begIdx, endIdx;

       // search beginning of the first word
       begIdx = line.find_first_not_of(delims);

       // while beginning of a word found
       while (begIdx != string::npos)
       {
           // search end of the actual word
           endIdx = line.find_first_of (delims, begIdx);
           if (endIdx == string::npos)
           {
               // end of word is end of line
               endIdx = line.length();
           }

           // print characters in reverse order
           for (int i=endIdx-1; i>=static_cast<int>(begIdx); --i)
           {
               cout << line[i];
           }
           cout << ' ';

           // search beginning of the next word
           begIdx = line.find_first_not_of (delims, endIdx);
       }
       cout << endl;
   }
}
/***************************************************
运行结果:
Enter a sentence (use <space> as the delimiter):
think out of the box
You entered: think
Enter a sentence (use <Enter> as the delimiter):
You entered: out of the box

******************************************
R*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.

******************************************
First non-alphabetic character is - at position 12

******************************************

please input a sentence :
I was a deer

after reverse:
I saw a reed
^Z

Process returned 0 (0x0)   execution time : 38.860 s
Press any key to continue.

****************************************************/

关于find_first_not_of

find_first_not_of 函数原型

#include <string> 

size_type find_first_not_of(const string &str,size_type index =0 )const; 

size_type find_first_not_of(const Char* str,size_type index =0 )const; 

size_type find_first_not_of(const Char* str,size_type index,size_type num )const; 

size_type find_first_not_of(Char ch,size_type index =0 )const; 

函数find_first_not_of()功能如下: 

1.返回在字符串中首次出现的不匹配str任何字符的首字符索引, 从index开始搜索, 如果全部匹配则返回string::npos。 

2.从index开始起搜索当前字符串, 查找其中与str前num个字符中的任意一个都不匹配的序列, 返回满足条件的第一个字符索引, 否则返回string::npos。 

3.返回在当前字符串中第一个不匹配ch字符的索引, 从index开始搜索, 没用收获则返回string::npos。

关于 npos:

The string class provides six search functions, each named as a variant of find. The operations all return a string::size_type value that is the index of where the match occurred, or a special value named string::npos if there is no match. The string class defines npos as a value that is guaranteed to be greater than any valid index.

string 类提供了 6 种查找函数,每种函数以不同形式的 find 命名。这些操作全都返回 string::size_type 类型的值,以下标形式标记查找匹配所发生的位置;或者返回一个名为 string::npos 的特殊值,说明查找没有匹配。string 类将 npos 定义为保证大于任何有效下标的值。

比如:

string str;

pos=str.find_first_of("h");

if(pos!=string::npos)

{..

....

} //npos是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 

//许多容器都提供这个东西。取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。npos表示string的结束位子,

//是string::type_size 类型的,也就是find()返回的类型。

Maximum value for size_t

npos is a static member constant value with the greatest possible value for an element of type size_t.

 This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

 As a return value, it is usually used to indicate no matches.

 This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

关于find_first_of

size_type find_first_of( const basic_string &str, size_type index = 0 ); 

 size_type find_first_of( const char *str, size_type index = 0 ); 

 size_type find_first_of( const char *str, size_type index, size_type num ); 

 size_type find_first_of( char ch, size_type index = 0 ); 

 find_first_of()函数: 

 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,如果没找到就返回string::npos 

 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,最多搜索num个字符。如果没找到就返回string::npos, 

 查找在字符串中第一个与ch匹配的字符,返回它的位置。搜索从index开始。

关于getline


1istream& getline (istream& is, string& str, char delim)
2istream& getline (istream& is, string& str);
Get line from stream into string

Extracts characters from is and stores them intostr until the delimitation characterdelim is found (or the newline character,'\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

Each extracted character is appended to the string as if its member push_back was called.

 

std::getline (string)

(1)

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

(2)

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

Get line from stream into string

Extracts characters from is and stores them intostr until the delimitation characterdelim is found (or the newline character,'\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

Each extracted character is appended to the string as if its member push_back was called.

Parameters

is

istream object from which characters are extracted.

str

string object where the extracted line is stored.


原型

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

istream& getline ( istream& , string& );

参数

is 进行读入操作的输入流

str 存储读入的内容

delim 终结符

返回值

与参数is是一样的

功能

将输入流is中读到的字符存入str中,直到遇到终结符delim才结束。对于第一个函数delim是可以由用户自己定义的终结符;对于第二个函数delim默认为 '\n'(换行符)。

函数在输入流is中遇到文件结束符(EOF)或者在读入字符的过程中遇到错误都会结束。

在遇到终结符delim后,delim会被丢弃,不存入str中。在下次读入操作时,将在delim的下个字符开始读入

抱歉!评论已关闭.