您的位置:首页 > 其它

利用字符出现的次数,编写一个方法,实现基本的字符串压缩功能。

2014-05-29 10:18 846 查看
利用字符出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串为aabccccaaa,会变为a2b1c5a3.若“压缩”后的字符串没有变短,则返回原先的字符串。

1.使用stringstream将int转化为string

2

string (1)
string& append (const string& str);

substring (2)
string& append (const string& str, size_t subpos, size_t sublen);

c-string (3)
string& append (const char* s);

buffer (4)
string& append (const char* s, size_t n);

fill (5)
string& append (size_t n, char c);

range (6)
template <class InputIterator>
string& append (InputIterator first, InputIterator last);

initializer list(7)
string& append (initializer_list<char> il);

3.


std::string::push_back

void push_back (char c);


Append character to string
Appends character c to the end of the string, increasing its length by
one.

string StringCompress(const string &s)
{
string retStr;
if(s.length() == 0)
return retStr;
char tmpChar = s.at(0);
int charCount = 0;
for(string::const_iterator it = s.begin();it != s.end();it++)
{
if(*it ==tmpChar)
{
charCount++;
}
else
{
retStr.push_back(tmpChar);

//使用stringstream将int转化为string
stringstream ss;
ss<<charCount;
string tmpStr = ss.str();

retStr.append(tmpStr);
tmpChar = *it;
charCount = 1;
}

if (it == s.end()-1)
{
retStr.push_back(tmpChar);
//使用stringstream将int转化为string
stringstream ss;
ss<<charCount;
string tmpStr = ss.str();

retStr.append(tmpStr);
}

}

if (retStr.length()<s.length())
{
return retStr;
}
else
{
return s;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐