I am a good boy
The in place reverse would be
boy good a am I
Method1
First reverse the whole string and then individually reverse the words
I am a good boy
<------------->
yob doog a ma I
<-> <--> <-> <-> <->
boy good a am I
Here is some C code to do the same ....
/*
Algorithm..
1. Reverse whole sentence first.
2. Reverse each word individually.
All the reversing happens in-place.
*/
#include
void rev(char *l, char *r);
int main(int argc, char *argv[])
{
char buf[] = "the world will go on forever";
char *end, *x, *y;
// Reverse the whole sentence first..
for(end=buf; *end; end++);
rev(buf,end-1);
// Now swap each word within sentence...
x = buf-1;
y = buf;
while(x++ < end)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
// Now print the final string....
printf("%s\n",buf);
return(0);
}
// Function to reverse a string in place...
void rev(char *l,char *r)
{
char t;
while(l < r)
{
t = *l;
*l++ = *r;
*r-- = t;
}
}
Method2
Another way to do it is, allocate as much memory as the input for the final output. Start from the right of the string and copy the words one by one to the output.
Input : I am a good boy
< --
< -------
< ---------
< ------------
< --------------
Output : boy
: boy good
: boy good a
: boy good a am
: boy good a am I
The only problem to this solution is the extra space required for the output and one has to write this code really well as we are traversing the string in the reverse direction and there is no null at the start of the string to know we have reached the start of the string!. One can use the strtok() function to breakup the string into multiple words and rearrange them in the reverse order later.
Method3
Create a linked list like
| I | -> | < spaces > | -> | am | -> | < spaces > | -> | a | -> | < spaces > | -> | good | -> | < spaces > | -> | boy | -> | NULL |
Now its a simple question of reversing the linked list!. There are plenty of algorithms to reverse a linked list easily. This also keeps track of the number of spaces between the words. Note that the linked list algorithm, though inefficient, handles multiple spaces between the words really well.
87 comments:
This is different solution for the same problem but in c++. I hope people find it useful....
(sorry for no comments)
#include "iostream.h"
using namespace std;
void removefirstword(char InputString[],char Output[])
{
bool bStart = false;
static int mainindex = 0;
int index =0;
while((InputString[mainindex] != ' ')&&(InputString[mainindex] != '\0'))
{
Output[index++] = InputString[mainindex];
mainindex++;
}
Output[index] = '\0';
if(InputString[mainindex] == '\0')
{
InputString[0] = '\0';
return;
}
mainindex++;
}
void addtothelast(char InputString[], char Output[])
{
bool bEnd = false;
static int mainindex1 = 0;
int index(0);
while(Output[index] != '\0')
{
InputString[mainindex1++] = Output[index++];
if(InputString[mainindex1] == '\0')
{
bEnd = true;
break;
}
}
if(bEnd == false)
{
InputString[mainindex1++] = ' ';
}
}
bool Empty(char InputString[])
{
bool retvalue = false;
if(InputString[0] == '\0')
{
retvalue = true;
}
return (retvalue);
}
void Reverse(char InputString[])
{
char* pOutput = new char[sizeof(InputString)];
if(true == Empty(InputString))
{
return;
}
removefirstword(InputString,pOutput);
Reverse(InputString);
addtothelast(InputString,pOutput);
}
void main()
{
char InputString[] = "My name is Prathap";
Reverse(InputString);
printf("%s\n", InputString);
}
What about this one:
void Revstr(char str[])
{
//Reversing each word in the String
int i = 0,j = 0,k = 0,tmp;
char tmpstr[256]= "";
for (i = 0; str[i]!='\0';)
{
for (k= i; str[k]!= '\0' && str[k]!= ' ';k++);
tmp = k--;
for (;k>=i;k--)
tmpstr[j++] = str[k];
i = tmp;
tmpstr[j++] = str[i];
if (str[i]!='\0')
i++;
}
//Reverse the whole string
return strrev(tmpstr);
}
Yes exactly, in some moments I can reveal that I approve of with you, but you may be considering other options.
to the article there is still a suspect as you did in the downgrade issue of this demand www.google.com/ie?as_q=insulin extinction coefficient ?
I noticed the catch-phrase you suffer with not used. Or you partake of the dreary methods of development of the resource. I suffer with a week and do necheg
Nice solution in C !
[url=http://citizenblogs.com/?u=videoseanselm8]Watch Music Videos[/url] [url=http://www.pinskerdream.com/bloghoster/?u=videoseallyson7]ImTOO DVD Creator 3.0.31.0824[/url]
Apex Video Converter Super 6.14 Real Player 11 Plus Gold Premium 2008
http://blog.bakililar.az/videosealbertina2/ YouRecorder
[url=http://www.blogportalen.no/blog/?u=videoseanissa1]Aone Ultra Mobile 3GP Video Converter 3.0.4.0421b[/url] [url=http://www.blogportalen.no/blog/?u=videosealberta1]Clone My DVD 1.1[/url]
Virtual Edit ImTOO Apple TV Video Converter 3.1.28.0413b
http://www.pinskerdream.com/bloghoster/?u=videosealvin5 Flv Recorder
MixMeister Fusion + Video 7.0.5.0
my icq:858499940385
here is the simple MATRIX method to reverse the sentance....no pointers no confusion......
#include
#include
#include
void main()
{
char s[50],str[50][50];
int len,i=0,j=0,k=0,l=0,p=0,m;
clrscr();
printf("Enter the sentence\n");
gets(s);
len=strlen(s);
while(i=0)
{ p=0;
while(str[l][p]!='\0')
{
printf("%c",str[l][p]);
p++;
}
printf(" ");
l--;
}
getch();
}
/*#include
#include
#include
void main()
{
char s[50],str[50][50];
int len,i=0,j=0,k=0,l=0,p=0,m;
clrscr();
printf("Enter the sentence\n");
gets(s);
len=strlen(s);
while(i=0)
{ p=0;
while(str[l][p]!='\0')
{
printf("%c",str[l][p]);
p++;
}
printf(" ");
l--;
}
getch();
}*/
Hi Guys... to post full prog ... previous of mine...
#include "stdio.h"
#include "stdlib.h"
char str[20]="Hi wise hungry boy";
int
reverse(int pos)
{
int strl = strlen(str)-1,i;
int substrstart = 0,substrend = 0;
char temp;
for(;;)
{
if( pos <= strl/2){
temp = str[pos];
str[pos]= str[strl-pos];
str[strl-pos] = temp;
}
else
break;
pos++;
}
for(;substrend-1 <= strl;)
{
if(str[substrend] == ' ' || str[substrend] == '\0')
{
for(i = 0; i <= ((substrend-1) - substrstart)/2; i++)
{
temp = str[substrstart+i];
str[substrstart+i] = str[(substrend-1)-i];
str[(substrend-1)-i] = temp;
}
if(str[substrend] == '\0')
{
break;
}
substrstart=substrend+1;
}
substrend++;
}
return 0;
}
void
main(int argc, char **argv)
{
printf("before string reverse: \n%s\n",str);
reverse(0);
printf("after string reverse: \n%s\n",str);
}
results below
before string reverse:
Hi wise hungry boy
after string reverse:
boy hungry wise Hi
Хороший пост! Подчерпнул для себя много нового и интересного! Пойду ссылку другу дам в аське :)
i got a couple of avi files that i cannot watch on my laptop that has Windows Vista and media player. please help!
[url=http://www.topvideoconverter.com/youtube-mate/]convert youtube video[/url]
Exactly I have searched for. I will be well prepared for my interview :)
#include
#include
#define SIZE 1000
int main()
{
char verse[45];
int ptr[50][SIZE ];
int i=0;
int j;
puts("ENTER A LINE OF TEXT BELOW: ");
gets(verse);
ptr[0][SIZE ]=strtok(verse," ");
while(ptr[i][SIZE ] != NULL)
{
ptr[i+1][SIZE ]=strtok(NULL," ");
i++;
}
for(j=i-1;j>=0;j--)
{
printf("%s ",ptr[j][SIZE ]);
}
return 0;
}
Hi! Thanks so much for taking the time to share your post; this posting has evoked the most response.
guys plz check out this :
#include
#include
#include
void rev(char *,char *);
int main()
{
int s,i=0;
int count=0;
char name[10][30], *end, *start;
printf("enter the text\n");
while(1)
{
gets(name[i]);
if(name[i][0]=='\0')
break;
i++;
}
for(s=0;s<=i;s++)
{
end=name[s];
start=name[s];
for(end =name[s];*end !='\0';end++)
if(*end=='\0' || *end ==' ')
{
rev(start,end-1);
start=end+1;
}
count= strlen(name[s]);
end=name[s]+count-1;
rev(start,end);
}
printf("\nthe reverse order is : \n");
for(s=0;s<=i;s++)
puts(name[s]);
return(0);
}
void rev(char *l ,char *m)
{
char t;
while(l<m)
{
t = *l;
*l++ = *m;
*m-- = t ;
}
}
Hi, thank you for sharing this great info. Was just browsing through the net in my office and happened upon your blog. It is really very well written and quit comprehensive in explaining with a very simple language.
I WILL SHOW YOU ONLY THE LOGIC...
Reversing a String -- DIRECT
int i=0,j,k;
char revstr[];
char str[]=" My name is Bond";
j=strlen(str); //15
while(j<0)
{
j--;
while(str[j]!='') //traverse till blank space
--j;
srt[j]='\0'; //you need to make the blank space null
k=j;
while(str[++k]!='\0')
{
revstr[i++]=str[k];
}
revstr[i++]='';
}
#include
main()
{char str[]= "I LUV U";
int i,k,l;
char j;
clrscr();
j=strlen(str);
for(i=j-1;i>=0;i--)
{k=i;
if(str[k]==' ')
{l=k;
while(str[k+1]!='\0' )
{ printf("%c",str[k+1]);
k++;
}
printf(" ");
str[l]='\0';
}}
printf("%s",str);
getch();
}It is easy to understand i hope
This might Help You ...
http://user-interfaze.blogspot.com/2012/01/c-program-to-reverse-string-word-by.html
If you're the type who never throws out anything that still fits, you may find a few vintage Lurex items in your own wardrobe. http://www.manyghdhair.com The show was filled with many talented designers and theirunique, inspired and fashion forward collections. north face uk The team at Mercedes Benz Fashion Festival (MBFF) can make all your dreams come true and we were lucky enough to secure a few of their very special VIP tickets last night!. north face outlet You can also do this with belly, but again, it needs to be thick.. ghd hair straightener Except in this case, we get revenge, Cronenberg body horror style.
Doing this night after night was pretty cray, but I loved every minute of it. north face backpacks One imagines oneself strolling down Comm Ave, resplendent in cardigans, jackets, scarves, and boots that aren necessary, per se (like they will be in January windstorms), but worn simply because one could not wait to pull them out again. ghd radiance set The above photo also provides a clue to the other major pick-me-up of the weekend: the first Spiders yarn-dying party at Marie house. north face coats They also supply further info about the products in an try to completely inform the client about the product that they are getting. ugg feel it been a really long time coming, but it feels like it was meant to happen now.
"Fashion Police: The 69th Annual Golden Globe Awards" premieres Monday, January 16 at 9pm ET/PT on E!. north face outlet Failing to get the most out of your current store ordered related equipment? Be it a supplementary feedback drive on rack web servers at the IT startup, that much-needed degree gauge in your jet boat panel, or just your etched company logo on the custom made color guitar amp at the acoustic guitar retail outlet, in some cases, inventory just can achieve it. north face backpacks They do this for reasons of diversity, to fill needs within important extra-curricular activities, to consider students who come from economically disadvantaged backgrounds, and even to admit non-traditional students who are applying to college after being out of school for several years.. ghd A dark sky can be interpreted as solitude or despair, while a bright sky with fluffy clouds may be interpreted as happiness and warmth.. ugg uk I also like to run a search on all of the coupon sites before making an online purchase, you never know what sales code might turn up.
Making a pair of lovely and unique lampwork beads earrings in person is not such a difficult thing. ghd nz sale Or, try Essie nail polish in Aruba Blue.. uggs (p. ghd australia When everything fall into place and things were going great guns, the Chopra family and the entire film industry shook with the death of the filmmaker. http://www.wellnorthface.com What interesting is that is sends out tweets from the woman vagina.
Nevertheless, now with color lenses you can change your eye color in split seconds. north face backpacks So, to cut a not very long story short, we went out a couple of times, he came round to my apartment one evening where we drank a bottle or two of wine, I showed him the tattoo on my thigh, he stroked my hysterectomy scar and said it was sexy, put his arm round me, I talked about work, pretending none of this was happening, then we started kissing and stumbled down the hall into my bed. http://www.oneghdhair.com You have to isolate yourself so you can really intensely focus, stay in your studio and work, and then you have to be this very social person in order to present your line. ugg boots Jan Boelo, only 24 years of age, has had his by fire only a year ago at AIFW 2011. http://www.verynorthface.com Arguments like "I only need a necklace" is a good point but there might come a time in the immediate future that the other items in the set will come in handy.
Calvin Klein Leopard Cosmetic Case Make Up Bag ~ Multi In Color Cute Calvin Klein Portable Travel Large Capacity Leopard Pattern Makeup Cosmetic Bag. ugg canada If you blown your temper, your chocolates won release. ugg boots Strictly a one-night only show with no further addition of tickets, this concert will mark the first time ever that 2NE1 are coming to Malaysia.. ghd hair straighteners Maybe he take pity on my hapless out-of-touch state and let me finish before I go back to breaking rocks packing the kitchenware boxes. http://www.wellnorthface.com hopefully, in a few years, she can fully realize those dreams as a stylist or designer as long as Childhood Cancer Awareness Month gets the attention it deserves.
Fashion trends come and go and sometimes they come back again. ghd hair straighteners I love the tagline, Your Story? In a digital age, you would think the novel would become obselete, but what Out Of Print is doing ironically, is to keep the novel alive and that to me is one worthy cause (it is pretty clever marketing if you think about it. http://www.wellnorthface.com It's so much fun to find a designer item at a bargain price. http://www.oneghdhair.com Prema ugovoru CEDEFa i kompanije pokrovitelja konkurasa, CEDEF se obavezuje da organizuje i sprovede sve aktivnosti u vezi sa nagradnim medijskim konkursom, dok je kopmanija pokrovitelj u obavezi da realizuje nagradu.. ugg boots The duo thought their pink clothes, small dogs and street smarts would make them instantly fit in and feel at home.
buy viagra online best buy generic viagra - viagra for women price
discount viagra buy viagra online perscription - generic viagra shipped to us
viagra online without prescription viagra for women pills - buy viagra us sites
viagra online without prescription viagra online generic us - how to buy viagra in usa
buy soma order soma from usa - cheap sheraton soma bay
cheap generic soma buy somatropin cheap - generic soma 250mg
I wanted to inform you how much my spouse and i appreciate all you've contributed to help improve lives of men and women in this subject matter. Through your own articles, we've gone out of just a beginner to a professional in the area. It can be truly a gratitude to your efforts. Thanks
Hello this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience. Any help would be enormously appreciated!
Well, not to get too anal about this, but Mikeyo said it was a myth that flat out didn't work.
Really wonderful style and design as well as remarkable material , nothing else necessary :).
Does your site have a contact page? I'm having a tough time locating it but, I'd like to shoot you an email. I've got some creative ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.
buy cialis online cialis online acquisto - cialis make you last longer
generic xanax blue xanax pills 031 - xanax identifier
generic xanax xanax usage - generic xanax xr 1mg
Lock your doors and home windows Even if you are gone to get a
short period of time of time. I have about 8 pair
lying about that I put on for all instances. It is really
uncomplicated to feeling stressed out from the Nike air max property-obtaining skills.
Prior to purchasing a residence, create some variables. http://www.
airmax90s2013.co.uk
buy carisoprodol does carisoprodol 350 mg have codeine - carisoprodol drug test
xanax no rx xanax overdose canine - will 1mg xanax do
carisoprodol 350 mg carisoprodol 350 mg photo - carisoprodol klonopin
buy tramadol tramadol 50 mg kapseln - 2 50mg tramadol
tadalafil no prescription buy legit cialis online - cialis online pharmacy
cialis online cheap cialis next day shipping - cialis overnight shipping
order tramadol no prescription tramadol hcl 377 - tramadol not addictive
buy tramadol online tramadol hcl 50mg tablet amnea - tramadol 50 mg vs percocet 5mg
order klonopin klonopin 2mg wiki - klonopin withdrawal webmd
learn how to buy tramdadol tramadol 50mg what is it for - tramadol hcl 50 mg information
http://landvoicelearning.com/#97734 tramadol 50mg street value - tramadol withdrawal how long does it last
http://landvoicelearning.com/#57594 buy tramadol online cod only - buy tramadol online no prescription cod
klonopin pill klonopin wafers prescribing information - klonopin withdrawal cold turkey
klonopin sale klonopin withdrawal in neonates - how many 2mg klonopin
http://www.integrativeonc.org/adminsio/buyklonopinonline/#buy klonopin withdrawal dry mouth - klonopin high duration
buy carisoprodol online without prescription buy cheap carisoprodol online - carisoprodol soma 350mg
Excellent beat ! I wish to apprentice whilst you amend
your website, how could i subscribe for a blog site? The account aided me
a acceptable deal. I had been a little bit acquainted of this your broadcast provided vibrant transparent concept
Here is my web blog: www.oakleyii.com
0qzkf1ss7
Review my webpage - best electric toothbrush
WexcoemeCer xaikalitag Laluttent [url=http://uillumaror.com]iziananatt[/url] escabbamS http://gusannghor.com gahfrauro
sac Louis Vuitton Louis Vuitton Sacs Louis Vuitton SacLouis Vuitton sacs
The report prονides vеrifiеd helpful to uѕ.
Ιt’s quitе uѕеful аnd you're simply naturally quite knowledgeable in this field. You have got popped my sight in order to varying opinion of this specific matter using interesting and sound articles.
Also visit my homepage ... viagra online
Feel free to visit my web-site : viagra online
Your current write-up has established helpful to mуsеlf.
It’s extremely useful and you're obviously extremely educated in this field. You have got exposed my own eye to various thoughts about this particular subject along with interesting and solid articles.
my homepage ... buy viagra online
My web site buy viagra online
[url=http://fantasy8013.com/forum.php?mod=viewthread&tid=200270]bag sales online[/url] the reason young women are probably so crazy about buyying settlement Cardy Ugg boots might be that the side by side-encountered true sheepskin applied in Ugg hiking footwear ensures they are particularly desirable. boots already have degree containing fleece jacket from inside so that it plush, passing difficult solace and they are bronzed from outside for a beautiful see. besides from this, UGG quarterly report fabricates and sells a brand of set of footwear for men and women. isn't day to day trainers these athletic shoes, comfortable hunter boots, Knit footwear, Chappals, crocs, sandals and more often. big money mention the popularity of UGG hunter boots, with a lot of famous people displaying these kind of. easily, advantages rate might that come with just about every pair of individuals healthy looking Cardy Ugg boot footwear, booties,hunter wellies is pretty obvious.
[url=http://www.90zzw.com/forum.php?mod=viewthread&tid=23970]hermes birkin bags uk[/url] 6. dealing with the university. alignment comes along first rate which will commuting individuals in the course. before the sessions start by, You are already aware what you should expect vacationing from your home to campus. You can view most convenient track, Or absolutely parent whether it would be better for you to stay in college.
[url=http://bbs.mych.com.cn/read.php?tid=317482]herm猫s bags[/url] a visit to amazon discoveries my PlayStation 3 buying for just a price tag price of $500 20-event vehicle and as well as $600 regarding 60-concerts, A plain differentiation path of the $2,000 and so they journeyed for facing the yuletide season. at this moment, leading Buy's internet demonstrates this the high-conclude super model tiffany livingston is entirely on outline.
Replaced the cartridge, very same issue with grinding.
Don't know just what to do because its 6 years old, and no actual repair work places. I may tear it apart and check out it. Many thanks.
my web-site ... xerox phaser 8560 yellow ink
Hi there, You have done a great job. I'll definitely digg it and personally recommend to my friends. I'm sure they will be benefited from this web site.
Review my web site: loss weight program
Excellent blog here! Additionally your website so much up very
fast! What web host are you the use of? Can I get your
affiliate hyperlink on your host? I desire my website loaded up as quickly as yours lol
Look at my homepage the tao of badass real
Link exchange is nothing else except it is simply placing the other person's weblog link on your page at appropriate place and other person will also do same for you.
Here is my web site Top 10 Best uk web Hosting companies
Howdy! I could have sworn I've been to this blog before but after going through some of the posts I realized it's new to me.
Nonetheless, I'm certainly happy I found it and I'll be
bookmarking it and checking back frequently!
my web-site; christian louboutin sneakers
Good post. I learn something totally new and challenging on websites I stumbleupon every day.
It's always interesting to read through articles from other authors and use a little something from their web sites.
Visit my site; christian louboutin wedges
Hey there! I know this is kinda off topic
however I'd figured I'd ask. Would you be interested in trading links or maybe guest writing
a blog post or vice-versa? My site covers a lot of the same topics as yours and I think we could greatly benefit from each other.
If you happen to be interested feel free to send me an e-mail.
I look forward to hearing from you! Wonderful blog
by the way!
Feel free to visit my web blog: the tao of badass
Greetings! This is my 1st comment here so I just wanted to give a quick shout out and tell you I really enjoy
reading through your blog posts. Can you recommend any other blogs/websites/forums that go over the same subjects?
Thanks a ton!
Also visit my web-site ... xerox 8560 service manual
Thanks for the marvelous posting! I certainly enjoyed reading it,
you might be a great author. I will ensure that I bookmark your blog and may
come back later on. I want to encourage continue your great
writing, have a nice evening!
vhs to avi
Thеre is cеrtaіnly a grеat deal tо find οut about this subject.
I liκe all thе points you mаԁе.
Fеel free tο ѕurf tο my blog .
.. jogos facebook
If you are going for finest contents like myself, only pay a visit this site everyday because it gives feature contents, thanks
Feel free to surf to my web-site: Ray Ban Outlet
Exactly how can I download and install a free of cost variation of hplaserjet 1020?
Also visit my page xerox phaser 8560 error codes
Wonderful work! That is the type of information that are
supposed to be shared across the web. Disgrace on the seek engines for now not positioning this submit higher!
Come on over and visit my site . Thank you =)
Feel free to surf to my web page; xerox 8560 phaser
I have a 51in Samsung plasma that i worked hard to get &
only had it a few the months.A remote flew out of my daughters hand & cracked screen.
The bottom of t.v. has lines & colors now.I have a two
year warranty but they said they wont fix it.Is it over for my t.
v. or can i do something?
Review my site 42 inch LS5600 ()
I have an inquiry on Avery Lables. I hase a few packs that have to do with 15 plus years old.
Never ever utilized any type of.
My web site xerox phaser 8560mfp driver ()
#include
#include
using namespace std;
int main()
{
char Sentence[100];
char *pSent;
char Temp[100];
gets(Sentence);
Temp[0] = '\0';
pSent = strrchr(Sentence,' ');
while(pSent != NULL)
{
strcat(Temp,pSent+1);
int Len = strlen(Temp);
Temp[Len] = ' ';
Temp[Len+1] = '\0';
Sentence[pSent - Sentence] = '\0';
pSent = strrchr(Sentence,' ');
}
strcat(Temp,Sentence);
cout<<Temp<<endl;
return 0;
}
smokeless cigarettes, e cig, ecigs, smokeless cigarette, e cigarette, e cigarette reviews
C++ Program to Reverse a Strings
Reverse a String means reverse the position of all character of String. You can use swapping concept to reverse any string in c++.
canada goose
supreme
nike vapormax
coach outlet store online
adidas yeezy
golden goose
nike shoes
air max 97
fila
michael jordan shoes
I’d need to talk with you here. Which is not some thing I usually do! I spend time reading an article that will get people to believe. Also, many thanks for permitting me to comment! allbarefootrunninggenuine
Hey just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the issue solved soon. Thanks expert-fiscal
Post a Comment