string类中replace,find,大小写转换等应用

本文详细介绍了C++中字符串的基本操作、find系列函数、find_first_of与find_first_not_of函数的应用,以及如何利用algorithm库中的transform函数进行字符串转换。通过实际代码示例展示了如何轻松实现字符串大写、小写转换等常见需求。

一、构造函数

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(int argc, char **argv)
{
	string s =  "123456789000";
	char str[] = "abcdefghijk";
	string s1 = s;
	//string s0(s, 3); 
	string s2(s, 3, 5); 
	printf("s = %s\n", s.c_str());
	cout<<"s1 = "<<s1<<endl;
	cout<<"s2 = "<<s2<<endl;

	cout<<"str = "<<str<<endl;
	string s4(str);
	cout<<"s4 = "<<s4<<endl;
	string s5(str, 5);
	cout<<"s5 = "<<s5<<endl;

	string s6(10, 'c');
	cout<<"s6 = "<<s6<<endl;

	//s.~string();
	//printf("s = %s\n", s.c_str());
	string s8 = s;
	s8.assign("abc12345");
	//printf("s = %s\n", s.c_str());
	printf("s8 = %s\n", s8.c_str());

	string s9 = s;
	s9.swap(s8);
	printf("s9 = %s\n", s9.c_str());
	printf("s8 = %s\n", s8.c_str());

	s9 += "tianmo";
	printf("s9 = %s\n", s9.c_str());
	s9.append(" hello world");
	printf("s9 = %s\n", s9.c_str());
	//可能vc 6.0不支持push_back()
	//'push_back' : is not a member of 'basic_string<char, \
	struct std::char_traits<char>,class std::allocator<char> >'
	//s9.push_back(" welcome to wuhan");
	//printf("s9 = %s\n", s9.c_str());

	//string& insert ( size_t pos1, const string& str, size_t pos2, size_t n ); 
	const char* s10 = s9.data();
	printf("s10 = %s\n", s10);

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

运行结果:


二、find()和repalce()函数

/***************************************************************************
 * 
 * Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved
 * 
 **************************************************************************/
 
 
 
/**
 * @file string.cpp
 * @author tianmo(com@baidu.com)
 * @date 2013/08/21 14:10:20
 * @brief 
 *  
 **/

#include <string>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
    const string suffix("tmp");

    string filename, basename, extname, tmpname;

    int i;
    for (i = 1; i < argc; ++ i) {
        //process and argument as file name
        filename = argv[i];

        //search period in file name
        string::size_type idx = filename.find('.');
        if (idx == string::npos) {
            //file name does not contain any period
            tmpname = filename + '.' + suffix;
        } else {
            //split file name into base name and extension
            //base name contains all characters beford the period
            //extension contains all characters after the period
            basename = filename.substr(0, idx);
            extname = filename.substr(idx + 1);

            if (extname.empty()) {
                //contains period but no extension append tmp
                tmpname = filename;
                tmpname += suffix;
            } else if (extname == suffix) {
                //replace extension tmp with ***
                tmpname = filename;
                tmpname.replace(idx + 1, extname.size(), "***");
            } else {
                //replace and extension with tmp
                tmpname = filename;
                tmpname.replace(idx + 1, string::npos, suffix);
            }
        }

        //print file name and temporary name
        cout<<filename<<" => "<<tmpname<<endl;
    }
    return 0;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
运行结果:


三、find_first_of()和find_first_not_of()

//从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置。查找失败返回string::npos
int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char *s, int pos = 0) const;
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;

//从当前串中查找第一个不在串s中的字符出现的位置,失败返回string::npos
int find_first_not_of(char c, int pos = 0) const;
int find_first_not_of(const char *s, int pos = 0) const;
int find_first_not_of(const char *s, int pos,int n) const;
int find_first_not_of(const string &s,int pos = 0) const;

//find_last_of和find_last_not_of与find_first_of和find_first_not_of相似,只不过是从后向前查找
int find_last_of(char c, int pos = npos) const;
int find_last_of(const char *s, int pos = npos) const;
int find_last_of(const char *s, int pos, int n = npos) const;
int find_last_of(const string &s,int pos = npos) const;

int find_last_not_of(char c, int pos = npos) const;
int find_last_not_of(const char *s, int pos = npos) const;
int find_last_not_of(const char *s, int pos,  int n) const;
int find_last_not_of(const string &s,int pos = npos) const;

/***************************************************************************
 * 
 * Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved
 * 
 **************************************************************************/
 
 
 
/**
 * @file print2word.cpp
 * @author tianmo(com@baidu.com)
 * @date 2013/08/21 14:48:36
 * @brief 
 *  
 **/
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
    const string delims(" \t,.;");

    string line;

    //for every line read successfully
    while(getline(cin, line)) {
        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;
    }
    return 0;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
运行结果:


将一个string转换成大写或者小写,是项目中经常需要做的事情,但string类里并没有提供这个方法。自己写个函数来实现,说起来挺简单,但做起来总让人觉得不方便。打个比方:早上起来想吃个汉堡,冰箱里有生牛肉,有面粉,也有微波炉,是可以自己做的,但是实在是太费事,没几个人愿意做。但是,打个电话给肯德基宅急送,10分钟后就有热乎乎的汉堡送上门了,大大节省了时间(时间就是金钱,你可以将时间用在更重要的开发工作上),并且味道也不差,何乐而不为呢?

       STL的algorithm库确实给我们提供了这样的便利,使用模板函数transform可以轻松解决这个问题,开发人员只需要提供一个函数对象,例如将char转成大写的toupper函数或者小写的函数tolower函数。


transform原型:

template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1, InputIterator last1,
                             OutputIterator result, UnaryOperator op );

template < class InputIterator1, class InputIterator2,
           class OutputIterator, class BinaryOperator >
  OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
                             InputIterator2 first2, OutputIterator result,
                             BinaryOperator binary_op );

测试代码:

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

int main()
{
    string strA = "yasaken@126.com";
    string strB = "LURY@LENOVO.com";
    printf("Before transform:\n");
    printf("strA:%s \n", strA.c_str());
    printf("strB:%s \n\n", strB.c_str());

    transform(strA.begin(), strA.end(), strA.begin(), ::toupper);
    transform(strB.begin(), strB.end(), strB.begin(), ::toupper);
    printf("After transform to toupper:\n");
    printf("strA:%s \n", strA.c_str());
    printf("strB:%s \n\n", strB.c_str());

    transform(strA.begin(), strA.end(), strA.begin(), ::tolower);
    transform(strB.begin(), strB.end(), strB.begin(), ::tolower);
    printf("After transform to lower:\n");
    printf("strA:%s \n", strA.c_str());
    printf("strB:%s \n\n", strB.c_str());
    return 0;
}
运行结果:

strA:yasaken@126.com 
strB:LURY@LENOVO.com 

After transform to toupper:
strA:YASAKEN@126.COM 
strB:LURY@LENOVO.COM 

After transform to lower:
strA:yasaken@126.com 
strB:lury@lenovo.com 

最后补一句:STL algorithm功能实在是太强劲了,非常推荐。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值