Jump to content

Freepascal string help

Zahuczky

Hey guys.
I recently started learning freepascal, and I'm going through a list of basic tasks, to learn the basics.
But I've found a simple task, that i can't solve, with the knowledge I have right now.
Simply, I want to read a string, that i give with write and read, and reverse the sentence.
Like, if i give "Hello everyone." it should spit out ".enoyreve olleH"
 

program untitled;
uses crt;
var s:string;
	i:integer;
	
BEGIN
	write('Phrase to reverse: ');
	readln(s);
	for i:=1 to length(s) do
	
	
END.

Thats how i started doing it, but i cannot find any ways to reverse it. 

Link to comment
Share on other sites

Link to post
Share on other sites

Thank you James. But i was just about to delete this topic, because i figured it out 5 seconds before your reply. 

Link to comment
Share on other sites

Link to post
Share on other sites

The simplest way - using a for-loop - is simply running a 'reverse' for loop

I am not sure exactly how Freepascal work, so apologies if I get some syntax wrong, but basically you want to do this:

var result: string;

for i := Length(s)-1 to 0 do
begin
	result = result + s[i];
end;

// Now you should print the string here

 

The idea behind this code is:

1. make a string, called result

2. loop through the string the user gave you

  - load i (index) with the length of that string (minus 1). The idea here is, you start at the end of your string (minus 1 because array starts at 0. So a 2 character long string, has array index 0 and 1) and work your way down (until 0)

3. save each entry in the string in 'result'  (in reverse order)

4. print this string

 

I now see you already got a fix, but I was halfway through my reply, so thought I would finish it.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

This one might also work, but with for loop using downto i got a much simpler code. And I'm pretty sure the guy who made these tasks, was looking for this answer
 

program untitled;
uses crt;
var s:string;
	i:integer;
	
BEGIN
	write('Phrase to reverse: ');
	readln(s);
	for i:=length(s) downto 1 do
	write(s[i]); 	
	
END.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×