【C++学习】字符串处理

简介: 作者:gnuhpc 出处:http://www.cnblogs.com/gnuhpc/ 1.思维导图: Example1: char *strcpy(char *target, const char *source) {   char *...

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

1.思维导图:

clip_image002

clip_image004

clip_image006

Example1:
char *strcpy(char *target, const char *source) {
  char *t = target;
  // Copy the contents of source into target.
  while(*source) *target++ = *source++;
  // Null-terminate the target.
  *target = '/0';
  // Return pointer to the start of target.
  return t;
}

Example2:
void *memmove(void *target, const void *source, size_t count)

这个函数即使是在源和目的字符串有所重叠时操作也能成功,虽然sourceconst,但是其指向的array也可能被修改。

2. C型字符串操作实例:

Ex1.基本操作

/* 
* ===================================================================================== 
* 
*       Filename:  2-1.cpp 
* 
*    Description:  Fundamental Operations in C Type String 
* 
*        Version:  1.0 
*        Created:  05/11/2010 10:43:11 AM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 
#include  
#include  

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    char strA[7]="UP"; 
    char strB[5]="DOWN"; 
    char strC[5]="LEFT"; 
    char strD[6]="RIGHT"; 

    /*Display */ 
    cout << "Here are the strings: " << endl; 
    cout << "strA: " << strA << endl; 
    cout << "strB: " << strB << endl; 
    cout << "strC: " << strC << endl; 
    cout << "strD: " << strD << "/n/n"; 

    //Display the length of strA. 
      cout << "Length of strA is " << strlen(strA) << endl; 
      cout << "Size of strA is " << sizeof(strA) << endl; 
    //Concatenate strB with strA 
    cout << "The result of Concatenate is strA::" << < 

    //Copy strC into strB,and partially strD into strA 
    cout << "The result of Copy is:" <<
    cout << "The result of partially Copy is strA:" << < 

    //Compare strC with strB 
    if( !strcmp(strC,strB)) 
    { 
        cout << "strC is equal to strB!"<
    } 

    if( !strncmp(strD,strA,3)) 
    { 
        cout << "strD is equal to strA partially!"<
    } 

    return 0; 

}

Ex2.搜索匹配相关操作

/* 
* ===================================================================================== 
* 
*       Filename:  2-2.cpp 
* 
*    Description:  Search Operation in C type String 
* 
*        Version:  1.0 
*        Created:  05/11/2010 11:38:15 AM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
int main(void) { 
  const char *url = "HerbSchildt.com"; 
  const char *url2 = "Apache.org"; 
  const char *emailaddr = "Herb@HerbSchildt.com"; 
  const char *tld[] = { ".com", ".net", ".org" }; 
  const char *p; 
  // First, determine if url and url2 contain .com, .net, or .org. 
  for(int i=0; i < 3; i++) { 
    p = strstr(url, tld[i]); 
    if(p) cout << url << " has top-level domain " << tld[i] << endl; 
    p = strstr(url2, tld[i]); 
    if(p) cout << url2 << " has top-level domain " << tld[i] << endl; 
  } 
  // Search for a specific character. 
  p = strchr(emailaddr, '@'); 
  if(p) cout << "Site name of e-mail address is: " << p+1 << endl; 
  // Search for any of a set of characters. In this case, 
  // find the first @ or period. 
  p = strpbrk(emailaddr, "@."); 
  if(p) cout << "Found " << *p << endl; 

  //Search for the beginning 
  if(strspn(url2,"Apache")==6){ 
    cout<< "Url2 begins with the /"Apache/""<< endl; 
  } 

  //与strchr正好倒过来 
  if(p=strrchr(emailaddr, 'b')){ 
    cout<< p << endl; 
  } 
  return 0; 
} 

Ex3.倒置一个字符串

我们用了四种方法,最后一种方法经常在面试笔试题中出现。

/* 
* ===================================================================================== 
* 
*       Filename:  2-3.cpp 
* 
*    Description:  Reverse a string 
* 
*        Version:  1.0 
*        Created:  05/12/2010 03:08:09 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 
#include 
#include 
using namespace std; 
void revstr(char *str); 
void revstr_p(char *str); 
void revstr_recursive(char *str, int start, int end); 
char *(revstrcpy)(char *rstr, const char *orgstr); 
int main() { 
  char str[] = "abcdefghijklmnopqrstuvwxyz"; 
  char *des= new char[27]; 
  cout << "Original string: " << str << endl; 
  revstr(str); 
  cout << "Reversed string: " << str << endl; 
  revstr_p(str); 
  cout << "Reversed string using pointer: " << str << endl; 
  revstr_recursive(str,0,strlen(str)-1); 
  cout << "Reversed string using recursive: " << str << endl; 
  cout << "Reversed string using copy method: " << revstrcpy(des,str)<< endl; 
  return 0; 
} 

void revstr(char *str) { 
  int i, j; 
  char t; 
  for(i = 0, j = strlen(str)-1; i < j; ++i, --j) { 
    t = str[i]; 
    str[i] = str[j]; 
    str[j] = t; 
  } 
} 

// Reverse a string in place. Use pointers rather than array indexing. 
void revstr_p(char *str) { 
  char t; 
  char *inc_p = str; 
  char *dec_p = &str[strlen(str)-1]; 
  while(inc_p <= dec_p) { 
    t = *inc_p; 
    *inc_p++ = *dec_p; 
    *dec_p-- = t; 
  } 
} 

void revstr_recursive(char *str, int start, int end) { 
  if(start < end) 
    revstr_recursive(str, start+1, end-1); 
  else 
    return; 
  char t = str[start]; 
  str[start] = str[end]; 
  str[end] = t; 
} 

char *(revstrcpy)(char *rstr, const char *orgstr) { //返回rstr的原始值使函数能够支持链式表达式,增加了函数的“附加值”。同样 
    功能的函数,如果能合理地提高的可用性,自然就更加理想。

  if((rstr==NULL)||(orgstr==NULL)) 
      throw "Invalid argument(s)"; 

  char *dst=rstr; 
  dst += strlen(orgstr); 
  *dst-- = '/0'; 
  while(*orgstr)  *dst-- = *orgstr++;  
  return rstr; 
}

Ex4.忽略大小写的字符串比较

/* 
* ===================================================================================== 
* 
*       Filename:  2-4.cpp 
* 
*    Description:  Ignore the Letter case when compared 
* 
*        Version:  1.0 
*        Created:  05/12/2010 03:44:34 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
int strcmp_ign_case(const char *str1, const char *str2); 
int main(void) { 
  char strA[]= "tesT"; 
  char strB[] = "Test"; 
  char strC[] = "testing"; 
  char strD[] = "Tea"; 
  int result; 
  cout << "Here are the strings: " << endl; 
  cout << "strA: " << strA << endl; 
  cout << "strB: " << strB << endl; 
  cout << "strC: " << strC << endl; 
  cout << "strD: " << strD << "/n/n"; 
  // Compare strings ignoring case. 
  result = strcmp_ign_case(strA, strB); 
  result = strcmp_ign_case(strA, strC); 
  result = strcmp_ign_case(strA, strD); 
  result = strcmp_ign_case(strD, strA); 
  return 0; 
} 
// A simple string comparison function that ignores case differences. 
int strcmp_ign_case(const char *str1, const char *str2) { 
  const char *str1_cp=str1; 
  const char *str2_cp=str2; 
  while(*str1_cp && *str2_cp) { 
    if(tolower(*str1_cp++) != tolower(*str2_cp++))  
      break; 
  } 
  int result=tolower(*str1_cp) - tolower(*str2_cp); 
  cout << str1 << " is "; 
  if(!result) 
    cout << "equal to "; 
  else if(result < 0) 
    cout << "less than "; 
  else  
    cout << "greater than "; 
  cout << str2 << endl; 
  return result; 
} 

Ex5.搜索替换

/* 
* ===================================================================================== 
* 
*       Filename:  2-5.cpp 
* 
*    Description:  Replace the sub_str with another str 
* 
*        Version:  1.0 
*        Created:  05/12/2010 04:07:02 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
#include 
using namespace std; 
bool search_and_replace(char *orgstr, int maxlen, 
                        const char *oldsubstr, const char *newsubstr); 
char *search_and_replace_alloc(const char *str, const char *oldsubstr, 
                               const char *newsubstr) throw(bad_alloc); 
int main(void) { 
    char str[80] = "alpha beta gamma alpha beta gamma"; 
    char *ptr=NULL; 
    cout << "Original string: " << str << "/n/n"; 
    cout << "First, replace all instances of alpha with epsilon./n"; 
  // Replace all occurrences of alpha with epsilon. 
    while(search_and_replace(str, sizeof(str), "alpha", "epsilon")) 
        cout << "After a replacement: " << str << endl; 
    cout << "Second, replace one instances of epsilon with alpha ./n"; 

    try { 
      ptr = search_and_replace_alloc(str, "epsilon", "alpha"); 
    } catch(bad_alloc exc) { 
      // Take appropriate action here. 
    } 
    if(ptr) { 
      cout << "After a replacement: " << ptr << endl; 
      delete [] ptr; 
    } 

    return 0; 
} 
bool search_and_replace(char *orgstr, int maxlen, 
                        const char *oldsubstr, const char *newsubstr) 
{ 
    char *pos=NULL; 
    if((orgstr==NULL)||(oldsubstr==NULL)||(newsubstr==NULL)) 
        return false;        
    int len = strlen(orgstr) - strlen(oldsubstr) + strlen(newsubstr); 
    if(len > maxlen) 
        return false; 
    if(pos=strstr(orgstr,oldsubstr)){ 
        memmove(pos+strlen(newsubstr),pos+strlen(oldsubstr),strlen(pos)-strlen(oldsubstr)+1);        
        strncpy(pos, newsubstr, strlen(newsubstr)); 
        return true; 
    } 
    else{ 
        return false; 
    } 
} 

char *search_and_replace_alloc(const char *str, const char *oldsubstr, 
                               const char *newsubstr) throw(bad_alloc) { 
    const char *pos=NULL; 
    if((str==NULL)||(oldsubstr==NULL)||(newsubstr==NULL)) 
        return NULL;        
    int size = strlen(str) + strlen(newsubstr) - strlen(oldsubstr) + 1; 
    char *result = new char[size]; 
    if(pos=strstr(str,oldsubstr)){ 
         strncpy(result, str, pos-str); 
         *(result+(pos-str)) = '/0'; 
         strcat(result, newsubstr); 
         strcat(result, pos+strlen(oldsubstr)); 
         cout<<RESULT<
         return result; 
    } 
    else { 
        delete [] result; 
        return NULL; 
    } 
}

Ex6.文本统计

/* 
* ===================================================================================== 
* 
*       Filename:  2-6.cpp 
* 
*    Description:  Text statistics Function 
* 
*        Version:  1.0 
*        Created:  05/13/2010 02:37:34 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 

struct wc { //不使用class是因为这是一个纯数据的对象,虽然它包含一个默认的构造函数。 
  int words; 
  int spaces; 
  int punct; 
  int lines; 
  wc() { 
    words = punct = spaces = lines = 0; 
  } 
}; 
wc wordcount(const char *str); 
int main() { 
  const char *test = "By supplying a string class and also " 
               "supporting null-terminated strings,/nC++ " 
               "offers a rich programming environment for " 
               "string-intensive tasks./nIt's power programming."; 
  cout << "Given: " << "/n/n"; 
  cout << test << endl; 
  wc wcd = wordcount(test); 
  cout << "/nWords: " << wcd.words << endl; 
  cout << "Spaces: " << wcd.spaces << endl; 
  cout << "Lines: " << wcd.lines << endl; 
  cout << "Punctuation: " << wcd.punct << endl; 
  return 0; 
} 
wc wordcount(const char *str) { 
  wc data;   

  if(*str) ++data.lines; 
  while(*str) {  

    if(isalpha(*str)) {  
      while(isalpha(*str) || *str == '/'') { 
        if(*str == '/'') ++data.punct; 
        ++str; 
      } 
      data.words++;  
    } 
    else {  
      if(ispunct(*str)) ++data.punct; 
      else if(isspace(*str)) { 
        ++data.spaces;  
        if(*str == '/n' && *(str+1)) ++data.lines; 
      } 
      ++str; 
    } 
  } 
  return data; 
}

Ex7 解析一个C型字符串

/* 
* ===================================================================================== 
* 
*       Filename:  2-7.cpp 
* 
*    Description:  String Token 
* 
*        Version:  1.0 
*        Created:  05/14/2010 10:01:58 AM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 

#define     MAX_TOKEN_SIZE 128 
const char *gettoken(const char *str); 
int main() { 
  char delims[] = "., ?;!"; 
  char str[] = "I like apples, pears, and grapes. Do you?"; 
  char *tok; 
  cout << "Obtain the words in a sentence./n"; 
  tok = strtok(str, delims); 
  while(tok) { 
    cout << tok << endl; 
    tok  = strtok(NULL, delims); 
  } 
  char kvpairs[] = "count=10, name=/"Tom Jones, jr./", max=100, min=0.01"; 
  char kvdelims[] = " =,"; 
  cout << "/nTokenize key/Value pairs./n"; 
  tok = strtok(kvpairs, kvdelims); 
  while(tok) { 
    cout << "Key: " << tok << " "; 
    if(!strcmp("name", tok)) { 
      tok = strtok(NULL, "/""); 
    } 
    else { 
      tok  = strtok(NULL, kvdelims); 
    } 
    cout << "Value: " << tok << endl; 
    tok = strtok(NULL, kvdelims); 
  } 

  cout <<"Ori String is " << kvpairs  <<>

  //We want to token the count ,12 and the symbol add(+),but we cannot make it via strtok 
  char count[]="max=12+3/89; count27 = 19*(min+floor);"; 
  char countdelims[]="=+"; 

  const char *strtok = gettoken(count); 
  while(strtok) { 
    cout << strtok << endl; 
    strtok  = gettoken(NULL); 
  } 
  cout << "/n/n"; 
  return 0; 
} 

const char *gettoken(const char *str) { 
  static char token[MAX_TOKEN_SIZE+1]; //static makes the return method can be made. 
  static const char *ptr; //static type holds the string last time passed in 
  int count= 0; // holds the current character count 
  char *tokptr=token; 
  if(str) { 
    ptr = str; 
  } 
  while(isspace(*ptr)) ptr++; 
  if(isalpha(*ptr)) { 
    while(isalpha(*ptr) || isdigit(*ptr)) { 
      *tokptr++ = *ptr++; 
      ++count; 
      if(count == MAX_TOKEN_SIZE) break; 
    } 
  } else if(isdigit(*ptr)) { 
    while(isdigit(*ptr)) { 
      *tokptr++ = *ptr++; 
      ++count; 
      if(count == MAX_TOKEN_SIZE) break; 
    } 
  } else if(ispunct(*ptr)) { 
    *tokptr++ = *ptr++; 
  } else return NULL; 
  // Null terminate the token. 
  *tokptr = '/0'; 
  return token;  
}

3. String操作实例:

Ex8 String基本操作

/* 
* ===================================================================================== 
* 
*       Filename:  2-8.cpp 
* 
*    Description:  String Basic Operation 
* 
*        Version:  1.0 
*        Created:  05/14/2010 02:15:06 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
int main() 
{ 
  // Create some string objects. Three are initialized 
  // using the string literal passed as an argument. 
  string str1("Alpha"); 
  string str2("Beta"); 
  string str3("Gamma"); 
  string str4; 
  // Output a string via cout. 
  cout << "Here are the original strings:/n"; 
  cout << "  str1: " << str1 << endl; 
  cout << "  str2: " << str2 << endl; 
  cout << "  str3: " << str3 << "/n/n"; 
  // Display the maximum string length. 
  cout << "The maximum string length is: " << str1.max_size() 
       << "/n/n"; 
  // Display the size of str1. You can use length() instead.这两个方法其实是一个效果,有size只是为了满足兼容STL的要求 
  cout << "str1 contains " << str1.size() << " characters./n"; 
  // Display the capacity of str1. 
  cout << "Capacity of str1: " << str1.capacity() << "/n/n"; 
  // Display the characters in a string one at a time 
  // by using the indexing operator. 
  for(unsigned i = 0; i < str1.size(); ++i) 
    cout << "str1["<<I<<"]: 
<< str1[i] ? />  // Concatenate two strings. 
  str4 = str1 + str3;  
  cout << "str4 after begin assigned st1+str3: " << str4 << "/n/n"; 
  // Insert one string into another. 
  str4.insert(5, str2); 
  cout << "str4 after inserting str2: " << str4 << "/n/n"; 
  // Obtain a substring. 
  str4 = str4.substr(5, 4); 
  cout << "str4 after being assigned str4.substr(5, 4): "  
       << str4 << "/n/n"; 
  // Compare two strings. 
  cout << "Compare strings./n"; 
  if(str3 > str1) cout << "str3 > str1/n"; //使用compare方法能够更加强大的比较String 
  if(str3 == str1+str2) 
    cout << "str3 == str1+str2/n"; 
  if(str1 <= str2) 
    cout << "str1 <= str2/n/n"; 
  // Create a string object using another string object. 
  cout << "Initialize str5 with the contents of str1./n"; 
  string str5(str1); 
  cout << "str5: " << str5 << "/n/n"; 
  // Erase str4. 
  cout << "Erasing str4./n"; 
  str4.erase(); //使用clear方法也可以 
  if(str4.empty()) cout << "str4 is now empty./n"; 
  cout << "Size and capacity of str4 is " << str4.size() << " " 
       << str4.capacity() << "/n/n"; 
  // Use push_back() to add characters to str4. 
  for(char ch = 'A'; ch <= 'Z'; ++ch) 
    str4.push_back(ch); 
  cout << "str4 after calls to push_back(): " << str4 << endl; 
  cout << "Size and capacity of str4 is now " << str4.size() << " " 
       << str4.capacity() << "/n/n"; 
  // Set the capacity of str4 to 128. 
  cout << "Setting the capacity of str4 to 128/n"; 
  str4.reserve(128); 
  cout << "Capacity of str4 is now: " << str4.capacity() << "/n/n"; 
  // Input a string via cin. 
  cout << "Enter a string: "; 
  cin >> str1; 
  cout << "You entered: " << str1 << "/n/n"; 
  return 0; 
}

Ex9 搜索操作

/* 
* ===================================================================================== 
* 
*       Filename:  2-9.cpp 
* 
*    Description:  Search String 
* 
*        Version:  1.0 
*        Created:  05/14/2010 03:16:12 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
void showresult(string s, string::size_type i); 
int main() 
{ 
  string::size_type indx; //这是很标准的使用方法,而不是使用int或者unsigned int 
  // Create a string. 
  string str("one two three, one two three"); 
  string str2; 
  cout << "String to be searched: " << str << "/n/n"; 
  cout << "Searching for the first occurrence of 'two'/n"; 
  indx = str.find("two"); 
  showresult(str, indx); 
  cout << "Searching for the last occurrence of 'two'/n"; 
  indx = str.rfind("two"); 
  showresult(str, indx); 
  cout << "Searching for the first occurrence of t or h/n"; 
  indx = str.find_first_of("th"); 
  showresult(str, indx); 
  cout << "Searching for the last occurrence of t or h/n"; 
  indx = str.find_last_of("th"); 
  showresult(str, indx); 
  cout << "Searching for the first occurrence of any character other " 
       << "than o, n, e, or space/n"; 
  indx = str.find_first_not_of("one "); 
  showresult(str, indx); 
  cout << "Searching for the last occurrence of any character other " 
       << "than o, n, e or space/n"; 
  indx = str.find_last_not_of("one "); 
  showresult(str, indx); 
  return 0; 
} 
// Display the results of the search. 
void showresult(string s, string::size_type i) { 
  if(i == string::npos) { //在没有匹配的部分都是返回npos 
    cout << "No match found./n"; 
    return; 
  } 
  cout << "Match found at index " << i << endl; 
  cout << "Remaining string from point of match: " 
       << s.substr(i) << "/n/n"; 
}

Ex10.搜索替换操作:

这个版本比C型字符串要简单许多,主要原因是String的动态特性和

/* 
* ===================================================================================== 
* 
*       Filename:  2-11.cpp 
* 
*    Description:  String Search and Replace 
* 
*        Version:  1.0 
*        Created:  05/14/2010 03:48:47 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
bool search_and_replace(string &str, const string &oldsubstr, 
                        const string &newsubstr); 
int main() 
{ 
  string str = "This is a test. So is this."; 
  cout << "Original string: " << str << "/n/n"; 
  cout << "Replacing 'is' with 'was':/n"; 
  // The following replaces is with was. Notice that 
  // it passes string literals for the substrings.  
  // These are automatically converted into string objects. 
  while(search_and_replace(str, "is", "was"))     
   cout << str << endl;   
  cout << endl; 
  // Of course, you can explicitly pass string objects, too. 
  string oldstr("So"); 
  string newstr("So too"); 
  cout << "Replace 'So' with 'So too'" << endl; 
  search_and_replace(str, oldstr, newstr); 
  cout << str << endl;   
  return 0; 
} 
bool search_and_replace(string &str, const string &oldsubstr, 
                        const string &newsubstr) { 
  string::size_type startidx; 
  startidx = str.find(oldsubstr); 
  if(startidx != string::npos) { 
    str.replace(startidx, oldsubstr.size(), newsubstr); 
    return true; 
  } 
  return false; 
}

Ex11.迭代器的基本使用

/* 
* ===================================================================================== 
* 
*       Filename:  2-13.cpp 
* 
*    Description:  String Iterator 
* 
*        Version:  1.0 
*        Created:  05/14/2010 04:55:41 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 
#include 
#include 
#include 
#include 
#include 
using namespace std; 
int main() 
{ 
  string strA("This is a test."); 
  // Create an iterator to a string. 
  string::iterator itr; 
  // Use an iterator to cycle through the characters  
  // of a string. 
  cout << "Display a string via an iterator./n"; 
  for(itr = strA.begin(); itr != strA.end(); ++itr)  
    cout << *itr; 
  cout << "/n/n"; 
  // Use a reverse iterator to display the string in reverse. 
  cout << "Display a string in reverse using a reverse iterator./n"; 
  string::reverse_iterator ritr; 
  for(ritr = strA.rbegin(); ritr != strA.rend(); ++ritr) 
    cout << *ritr; 
  cout << "/n/n"; 
  // Insert into a string via an iterator. 
  // First, use the the STL find() algorithm to obtain 
  // an iterator to the start of the first 'a'. 
  itr = find(strA.begin(), strA.end(), 'a'); 
  // Next, increment the iterator so that it points to the 
  // character after 'a', which in this case is a space.   
  ++itr; 
  // Insert into str by using the iterator version of insert().  
  cout <<"Insert into a string via an iterator./n"; 
  string strB(" bigger"); 
  strA.insert(itr, strB.begin(), strB.end()); 
  cout << strA << "/n/n"; 
  // Now, replace 'bigger' with 'larger'. 
  cout << "Replace bigger with larger./n"; 
  itr = find(strA.begin(), strA.end(), 'b'); 
  strA.replace(itr, itr+6, "larger"); 
  cout << strA << "/n/n"; 
  // Now, remove ' larger'. 
  cout << "Remove ' larger'./n"; 
  itr = find(strA.begin(), strA.end(), 'l'); 
  strA.erase(itr, itr+7); 
  cout << strA << "/n/n"; 
  // Use an iterator with the STL transform() algorithm to convert 
  // a string to uppercase. 
  cout << "Use the STL transform() algorithm to convert a " 
       << "string into uppercase./n";       
  transform(strA.begin(), strA.end(), strA.begin(), toupper); 
  cout << strA << "/n/n"; 
  // Create a string from a vector. 
  vector vec; 
  for(int i=0; i < 10; ++i) 
    vec.push_back('A'+i); 
  string strC(vec.begin(), vec.end()); 
  cout << "Here is strC, which is constructed from a vector:/n"; 
  cout << strC << endl; 
  return 0; 
} 

Ex12忽略大小写的搜索替换

/* 
* ===================================================================================== 
* 
*       Filename:  2-14.cpp 
* 
*    Description:  Search and Replace a substring ignoring the case 
* 
*        Version:  1.0 
*        Created:  05/14/2010 07:10:20 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
#include 
#include 
using namespace std; 
bool comp_ign_case(char x, char y); 
string::iterator search_ign_case(string &str, const string &substr); 
bool search_and_replace_ign_case(string &str, const string &oldsubstr, 
                                 const string &newsubstr); 
int main() 
{ 
  string strA("This is a test of case-insensitive searching."); 
  string strB("test"); 
  string strC("TEST"); 
  string strD("testing"); 
  cout << "First, demonstrate search_ign_case()./n"; 
  cout << "String to be searched:/n" << strA << "/n/n"; 
  cout << "Searching for " << strB << ". "; 
  if(search_ign_case(strA, strB) != strA.end()) 
    cout << "Found!/n"; 
  cout << "Searching for " << strC << ". "; 
  if(search_ign_case(strA, strC) != strA.end()) 
    cout << "Found!/n"; 
  cout << "Searching for " << strD << ". "; 
  if(search_ign_case(strA, strD) != strA.end()) 
    cout << "Found!/n"; 
  else 
    cout << "Not Found./n"; 
  // Use the iterator returned by search_ign_case() to display 
  // the remainder of the string. 
  cout << "/nRemainder of string after finding 'of':/n"; 
  string::iterator itr = search_ign_case(strA, "of"); 
  while(itr != strA.end())  
    cout << *itr++; 
  cout << "/n/n"; 
  // Now, demonstrate search and replace. 
  strA = "Alpha Beta Gamma alpha beta gamma"; 
  cout << "Now demonstrate search_and_replace_ign_case()./n"; 
  cout << "String that will receive replacments:/n" << strA << "/n/n"; 
  cout << "Replacing all occurrences of alpha with zeta:/n"; 
  while(search_and_replace_ign_case(strA, "alpha", "zeta")) 
    cout << strA << endl; 
  return 0; 
} 
string::iterator search_ign_case(string &str, const string &substr) { 
  return search(str.begin(), str.end(), 
                substr.begin(), substr.end(), 
                comp_ign_case); 
}   
bool comp_ign_case(char x, char y) { 
  return tolower(x) == tolower(y); 
} 
bool search_and_replace_ign_case(string &str, const string &oldsubstr, 
                        const string &newsubstr) { 
  string::iterator startitr; 
  startitr = search_ign_case(str, oldsubstr); 
  if(startitr != str.end()) { 
    str.replace(startitr, startitr+oldsubstr.size(), newsubstr); 
    return true; 
  } 
  return false; 
}

Ex13String转化为普通字符串

/* 
* ===================================================================================== 
* 
*       Filename:  2-15.cpp 
* 
*    Description:  Convert String to the C type string using c_str 
* 
*        Version:  1.0 
*        Created:  05/16/2010 03:10:12 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 
#include 
#include 
#include 
using namespace std; 
int main() 
{ 
  string str("This is a test."); 
  char cstr[80]; 
  cout << "Here is the original string:/n"; 
  cout << str << "/n/n"; 
  // Obtain a pointer to the string. 
  const char *p = str.c_str(); 
  cout << "Here is the null-terminated version of the string:/n"; 
  cout << p << "/n/n"; 
  // Copy the string into a statically allocated array. 
  // 
  // First, confirm that the array is long enough 
  // to hold the string. 
  if(sizeof(cstr) < str.size() + 1) { 
    cout << "Array is too small to hold the string./n"; 
    return 0; 
  } 
  strcpy(cstr, p); //因为返回的是const类型, 通常我们需要将这个字符串拷贝出来 
  cout << "Here is the string copied into cstr:/n" << cstr << "/n/n"; 
  // Next,copy the string into a dynamically allocated array. 
  try { 
    // Dynamically allocate the array. 
    char *p2 = new char[str.size()+1]; 
    // Copy the string into the array. 
    strcpy(p2, str.c_str()); 
    cout << "String after being copied into dynamic-allocated array:/n"; 
    cout << p2 << endl; 
    delete [] p2; 
  } catch(bad_alloc ba) { 
    cout << "Allocation Failure/n"; 
    return 1; 
  } 
  return 0; 
}

Ex14为String重载减法运算

/* 
* ===================================================================================== 
* 
*       Filename:  2-16.cpp 
* 
*    Description:  Override the - and -= operation in String 
* 
*        Version:  1.0 
*        Created:  05/16/2010 03:38:14 PM 
*       Revision:  none 
*       Compiler:  gcc 
* 
*         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com 
*        Company:  IBM CDL 
* 
* ===================================================================================== 
*/ 

#include 
#include 
using namespace std; 
string operator-(const string &left, const string &right); 
string operator-=(string &left, const string &right); 
int main() 
{ 
  string str("This is a test."); 
  string res_str; 
  cout << "Contents of str: " << str << "/n/n"; 
  // Subtract "is" from str and put the result in res_str.   
  res_str =  str - "is"; 
  cout << "Result of str - /"is/": " << res_str << "/n/n"; 
  // Use -= to subract "is" from res_str. This puts the result 
  // back into res_str. 
  res_str -= "is"; 
  cout << "Result of res_str -= /"is/": " << res_str << "/n/n"; 
  return 0; 
} 
string operator-(const string &left, const string &right) { 
  string::size_type i; 
  string result(left); 
  i = result.find(right); 
  if(i != string::npos)  
    result.erase(i, right.size()); 
  return result; 
} 
string operator-=(string &left, const string &right) { 
  string::size_type i; 
  i = left.find(right); 
  if(i != string::npos)  
    left.erase(i, right.size()); 
  return left; 
} 

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/


               作者:gnuhpc
               出处:http://www.cnblogs.com/gnuhpc/
               除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。


分享到:

目录
相关文章
|
4月前
|
算法 C语言 C++
C++语言学习指南:从新手到高手,一文带你领略系统编程的巅峰技艺!
【8月更文挑战第22天】C++由Bjarne Stroustrup于1985年创立,凭借卓越性能与灵活性,在系统编程、游戏开发等领域占据重要地位。它继承了C语言的高效性,并引入面向对象编程,使代码更模块化易管理。C++支持基本语法如变量声明与控制结构;通过`iostream`库实现输入输出;利用类与对象实现面向对象编程;提供模板增强代码复用性;具备异常处理机制确保程序健壮性;C++11引入现代化特性简化编程;标准模板库(STL)支持高效编程;多线程支持利用多核优势。虽然学习曲线陡峭,但掌握后可开启高性能编程大门。随着新标准如C++20的发展,C++持续演进,提供更多开发可能性。
86 0
|
2月前
|
编译器 C语言 C++
配置C++的学习环境
【10月更文挑战第18天】如果想要学习C++语言,那就需要配置必要的环境和相关的软件,才可以帮助自己更好的掌握语法知识。 一、本地环境设置 如果您想要设置 C++ 语言环境,您需要确保电脑上有以下两款可用的软件,文本编辑器和 C++ 编译器。 二、文本编辑器 通过编辑器创建的文件通常称为源文件,源文件包含程序源代码。 C++ 程序的源文件通常使用扩展名 .cpp、.cp 或 .c。 在开始编程之前,请确保您有一个文本编辑器,且有足够的经验来编写一个计算机程序,然后把它保存在一个文件中,编译并执行它。 Visual Studio Code:虽然它是一个通用的文本编辑器,但它有很多插
|
2月前
|
Java 编译器 C++
c++学习,和友元函数
本文讨论了C++中的友元函数、继承规则、运算符重载以及内存管理的重要性,并提到了指针在C++中的强大功能和使用时需要注意的问题。
24 1
|
5月前
|
存储 安全 编译器
【C++入门 四】学习C++内联函数 | auto关键字 | 基于范围的for循环(C++11) | 指针空值nullptr(C++11)
【C++入门 四】学习C++内联函数 | auto关键字 | 基于范围的for循环(C++11) | 指针空值nullptr(C++11)
|
5月前
|
人工智能 分布式计算 Java
【C++入门 一 】学习C++背景、开启C++奇妙之旅
【C++入门 一 】学习C++背景、开启C++奇妙之旅
|
5月前
|
存储 自然语言处理 编译器
【C++入门 三】学习C++缺省参数 | 函数重载 | 引用
【C++入门 三】学习C++缺省参数 | 函数重载 | 引用
|
5月前
|
小程序 C++
【C++入门 二 】学习使用C++命名空间及其展开
【C++入门 二 】学习使用C++命名空间及其展开
|
5月前
|
存储 C++ 索引
|
5月前
|
存储 C++ 容器
|
5月前
|
算法 数据处理 C++