Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
suppose my str holds:
str="helloHowAreYou";
Now i want to shift the indexes of the string to backward from a particular position and
my new string will contain.
str="heoHowAreYou".
My code output is str="heoHowAreYou Y",
Any help will be appreciated

What I have tried:

#include <iostream>
#include<cstring>
using namespace std;
void shift(string arr,int be)
{
    int j=be;
    while(arr[j]!='\0')
    {
        j++;
    }
    int k=j-2;
    while(be<=k)
    {
        arr[be]=arr[be+2];
        be++;
    }
    cout<<arr;

}
int main(int argc, char const *argv[])
{
    string str;
    str="helloHowAreyou";
    shift(str,2);
    return 0;
}
Posted
Updated 19-Jun-17 21:42pm

As far as I understand your code, it can't produce the stated output.
A part of your problem os that you don't reduce the length of your string.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
Your example removes 2 characters at position 2.

There is a std::string method that can do that: std::basic_string::erase - cppreference.com[^]:
string str = "helloHowAreyou";
str.erase(2, 2);
cout << str;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900