Home > other >  Given a string, remove a the repeating consecutive characters using c
Given a string, remove a the repeating consecutive characters using c

Time:11-03

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
    string s;
    getline(cin,s);
    int n= s.length();
    string ans;
    ans[0]=s[0];
    int j=1;
    for(int i=1; i<n; i  ){
        if(s[i]!=s[i-1]){
            ans[j]=s[i];
            j  ;
        }
    }
    ans[n]='\0';
    cout<<ans<<endl;
    // for(int i=0; i<n; i  ){
    //  cout<<ans[i];
    // }
    cout<<endl;
    return 0;
}

I am not able to print the variable ans using simple cout<<ans<<endl. Instead I have to use a loop to print it. Why is that?

CodePudding user response:

Here

string ans;

ans is a string of lenght 0. Already in the next line you invoke undefined behavior by trying to modify an element beyond the end of the string:

ans[0]=s[0];

You can add characters to a string via ans = character; or ans.push_back(character);. You cannot print ans via std::cout because you never add a character to it.

CodePudding user response:

I'm not sure about C but in C strings are character array. So let's say you define a string like this:

char ans[]="Hello";

It'll store the string in form of an array of characters while ans will be pointing to the first element of array.

The thing is array designators(the names you use for an array) are implicitly converted into pointer. So for string ans, it is not a whole container which stores the whole string Hello but instead it will be pointing to first block of group of sequentially arranged containers those hold H e l l o characters individually.

So if you print ans so it'll only give the data of the container it's pointing to instead of whole group of containers.

Although the answer is not that relevant I hope the concept helps.

  • Related