扩展c ++字符串成员函数 [英] extending c++ string member functions

查看:219
本文介绍了扩展c ++字符串成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要做一个不区分大小写的find,并发现了下面的代码,这是做的

  bool ci_equal ch1,char ch2)
{
return toupper((unsigned char)ch1)== toupper((unsigned char)ch2);
}

size_t ci_find(const string& str1,const string& str2)
{
string :: const_iterator pos = std :: search(str1。begin ),str1。end(),str2。
begin(),str2。end(),ci_equal);
if(pos == str1。end())
return string :: npos;
else
return pos - str1。开始 ( );
}

这让我想知道什么会使它成为一个成员函数'string',因此可以这样调用:

  string S =abcdefghijklmnopqrstuv; 
string F =GHI;

S.ci_find(F);

我意识到在非英语语言中的case转换有很多问题,但这不是问题有兴趣。



作为一个新手,我很快就迷失在容器和模板中。



反正要做到这一点?

解决方案

std :: string 不会被扩展。



你可以将std :: string封装到你的类中,并在该类中设置那些成员函数。

I had a need to do a case insensitive find and found the following code which did the trick

bool ci_equal(char ch1, char ch2)
{
    return toupper((unsigned char)ch1) == toupper((unsigned char)ch2);
}

size_t ci_find(const string& str1, const string& str2)
{
    string::const_iterator pos = std::search(str1. begin ( ), str1. end ( ), str2.
    begin ( ), str2. end ( ), ci_equal);
    if (pos == str1. end ( ))
        return string::npos;
    else
        return pos - str1. begin ( );
}

That got me to wondering what it would take to make this a member function of 'string' so it could be called like this:

string S="abcdefghijklmnopqrstuv";
string F="GHI";

S.ci_find(F);

I realize that there are many problems with case conversions in non-English languages but that's not the question I'm interested in.

Being a neophyte, I quickly got lost among containers and templates.

Is there anyway to do this? Could someone point to me an example of something similar?

解决方案

std::string is not made to be extended.

You could encapsulate an std::string into a class of yours and set those member functions in that class.

这篇关于扩展c ++字符串成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆