Ms Cookie
Ms Cookie

Reputation: 3

Shifting char array right after "inserting" to a given position?

I've received a task, where I have to change every 5th character of a character array to = character and then shift the other elements of the array right, like this: I like fruit --> I lik=e fru=it.

I have trouble with how to shift the elements after the = characters. I was considering something similar to simple sorting, but I just can't imagine how to switch and which elements. Could you help me out, please? Thanks in advance!

I could complete the code this far:

#include<cstring>
#include<fstream>

int main(){
    
    char sentence[] = "I like fruit";
    int length = strlen(sentence);
    
    for(int i = 1; i < length; i++){
        if(i % 5 == 0){
            sentence[i] = '=';
        }
    }
    
    std::cout << sentence << '\n';
    
    return 0;
}

Upvotes: 0

Views: 267

Answers (1)

silverfox
silverfox

Reputation: 1662

From running your code, it can be seen that the characters would be replaced, not inserted.

Your code result:

Input : I like fruit

Output : I lik= fru=t

A viable way is to input a std::string, use substr() to split the input into segments of 5, then adding a = afterward.

The problem with using char[] is that it's of fixed size, meaning nothing can be added/removed from it (although you can still modified it normally). std::string is dynamic (in general it is a dynamic char array with a few differences), so it could change its size.

#include<string>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    string inp; cout << "Input : "; getline(cin, inp);
    int len = inp.length(); string res = "";

    for (int i = 0; i < len; i+=5)
    {
        string tmp = inp.substr(i, 5); //splitting the string
        if (tmp.size() == 5) {tmp += '=';} //adding '='
        res += tmp;
    }
    cout << res;
}

Output:

Input : I like fruit
I lik=e fru=it

More info : Difference between std::string and char[] in C++.

Upvotes: 2

Related Questions