+ 1
Explanation ؟
#include <iostream> using namespace std; #include <string> void compressString(char *sr, int n ) { int count1=1; for(int i=0; i<n-1; i++) { if(sr[i] == sr[i+1]) count1++; else { cout<<sr[i]<<count1; count1=1; } } } int main(void) { int n; cin>>n; char str[n+1]; cin>>str; compressString(str, sizeof(str)); return 0; }
13 Antworten
+ 2
Ok, focus on smaller stuff first, that's just natural.
+ 6
look at the first thing in the method. it is a comparison statement which sees is the character (sr[i]) is the same as the next. (sr[i+1])
If it is, it increments the count1 variable. If not, it outputs that character (as it is unique to the one before it), and resets the count1 variable.
+ 3
Ok, you always get a pair of char and int from the input.
You call the string fill constructor with these pairs and push the result into the output.
+ 1
Can be explained more؟
+ 1
//This is how I'd write it without changing it too much.
#include <iostream>
using namespace std;
#include <string>
void compressString(const string& sr)
{
if (sr.empty())
{
cout << "Empty input.";
exit(0);
}
int count = 1;
for (int i = 0; i != sr.length() - 1; i++)
{
if (sr[i] == sr[i + 1])
count++;
else
{
cout << sr[i] << count;
count = 1;
}
}
cout << sr.back() << count;
}
int main(void)
{
string str;
cin >> str;
compressString(str);
}
+ 1
You can write one and I give you feedback.
+ 1
What do you mean?
0
This is actually not the best code. But what it does is it always counts how big the sequence of a char is and outputs the char and its sequence count.
You have to enter the size of the string first because of the codes poor use of the standard library.
And the last char doesn't get processed.
0
can you write one "decompress"??
0
can you write one "decompress"??
0
oky
?
0
can you give me feedback?
i can't write.
0
i try
and i don't know 😓