【发布时间】:2015-06-09 23:29:58
【问题描述】:
在这个String 长度编码算法中,我无法理解字符串的奇怪行为。谁能解释一下字符串的用法?下面的第一个for loop 什么都不打印,而第二个打印正确。我尝试使用大小、长度和调整大小,但第一个 for loop 仍然没有打印任何内容。
#include <iostream>
using namespace std;
int main() {
// your code goes here
string str, newstr;
str="aabcccccaaa";
newstr[0]=str[0];
cout<<str;
int j = 1;
for (int i =0; i<str.length(); i++)
{
int count =1;
while(i+1 != str.length() && str[i] == str[i+1])
{
count++; i++;
}
newstr[j] = '0'+count;
if(i+1 != str.length())
{ newstr[j+1] = str[i+1];
j=j+1;
}
j=j+1;
}
cout<<"\nRun String:";
for(int i =0; i<newstr.size(); i++) // First For loop.
cout<<newstr[i];
for(int i=0; i<j; i++) // Second For loop.
cout<<newstr[i];
return 0;
}
【问题讨论】: