Dec 26, 2013 at 7:24pm Dec 26, 2013 at 7:24pm UTC
Hi,
I have a string like str="ABCDEFGHIJK";
need o/p like this str="CBAFEDIHGJK"
am getting "CBA" correctly after that its not printing anything.
can anyone check the following code and let me know where is the problem?
int main()
{
string str="ABCDEFGHIJK";
char str1[10],rev[10];
int n=str.length(),count=0,c=3,k=0,j=0;
for(int i=0;i<n;i++)
{
str1[i]=str[i];
count++;
cout<<str1[i]<<" and "<<count<<"and "<<c<<endl;
if(count==c)
{
cout<<"Entered into if loop"<<count<<"and"<<c<<"and "<<k<<endl;
//c=c+k;
//j=0;
cout<<c<<" and "<<k<<endl;
while(j<c)
{
rev[j]=str1[c-k-1];
cout<<rev[j]<<" and "<<str1[c-k-1]<<endl;
j++;
k++;
}
count=0;
}
/*else
{
if(count < c && str[i]=='\0')
{
for(int k=0;k<count;k++)
{
rev[k]=str1[count-1];
count--;
count=0;
}
}
}*/
}
cout<<"The string is: "<<rev<<endl;
return 0;
}
Please help me on this.
Dec 27, 2013 at 2:16am Dec 27, 2013 at 2:16am UTC
Hi L B,
In this link, it is showing only how to reversing complete string but in my case I need reverse only no.of characters
ABCDEFGHIJK ===> CBAFEDIHGJK (Ex: no.of chars=3)
Dec 27, 2013 at 2:22am Dec 27, 2013 at 2:22am UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "ABCDEFGHIJK" ;
reverse(s.begin(), s.begin()+3);
cout << s << endl;
}
http://ideone.com/jP2KhI
Last edited on Dec 27, 2013 at 2:22am Dec 27, 2013 at 2:22am UTC
Dec 27, 2013 at 2:35am Dec 27, 2013 at 2:35am UTC
HI naraku9333,
Thanks for replying but it is reversing only 1st 3 chars only after that it should be reverse DEF ==> FED and GHI==>IHG also and also should not use builtin functions.
Last edited on Dec 27, 2013 at 2:36am Dec 27, 2013 at 2:36am UTC
Dec 27, 2013 at 2:56am Dec 27, 2013 at 2:56am UTC
This looks like a job for
boost::offset_separator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <string>
#include <iterator>
#include <boost/tokenizer.hpp>
int main()
{
std::string s = "ABCDEFGHIJK" ;
int offsets[] = {3};
boost::offset_separator f(offsets, offsets+1);
typedef boost::token_iterator_generator<boost::offset_separator>::type Iter;
std::string result;
for (Iter i = boost::make_token_iterator<std::string>(s.begin(), s.end(), f); i != Iter(); ++i )
if (i->size() == 3)
result.append(i->rbegin(), i->rend());
else
result += *i;
std::cout << result << '\n' ; // CBAFEDIHGJK
}
demo:
http://coliru.stacked-crooked.com/a/d92ba766844c10d2
Last edited on Dec 27, 2013 at 2:56am Dec 27, 2013 at 2:56am UTC
Dec 27, 2013 at 3:06am Dec 27, 2013 at 3:06am UTC
L B@ My requirement like that only, need to reverse without using built-in functions.
Dec 27, 2013 at 3:36am Dec 27, 2013 at 3:36am UTC
HI naraku9333,
Thanks for your reply, its working but if I took 4 its not working. I will read no. of characters at execution time.
Dec 27, 2013 at 3:43am Dec 27, 2013 at 3:43am UTC
Why don't you just edit his example so it works for a variable number?