Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how can i shift the indexes in a string,suppose i have declared a string i.e

String str;
cin>>str;
//now,i want to modify the same string as i want to shift the elements in the
// string by a particular no.
//for example

str="hello";
// say shift 2 palaces from h.
str="h ello ";
//i do not want to use character array.

What I have tried:

// Any help will be appreciated.
Posted
Updated 19-Jun-17 0:31am
v2

If you need to insert blanks somewhere in the string (like your example suggests) then the string::insert method ( see string::insert - C++ Reference[^]) is your friend:
C++
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string s = "hello";
  s.insert(1, 1, ' ');
  s.insert(s.end(), 1, ' ');
  cout << "'" << s << "'" << endl;
}
 
Share this answer
 
Your question is unclear.

Your example "he llo" is not shifted but has a space inserted. A shift operation would result in something like "ello" (shift left by one) or " hello" (shift right by one; may be also " hell" depending on the shift definition).

Check the methods provided by your String class. There might be functions that can be used (candidates are insert(), substr(), left(), right(), mid()).

Note also that a string class is usually nothing else than a dynamic character array.
 
Share this answer
 
It's going to depend on what environment your application is to run in: a CLR app could use one String class which has Substring functions, while a native app might have to use a different string class which supports substr instead.

But basically the operation will be along the lines of:
newstring = substring(original, 0, 1) + " " + substring(original, 1, lengthOfTheOriginalString - 1)

Check your classes for the exact functions and parameters to use.

And you do realise that in essence, any string is a character array?
 
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