MARIE Simulator answers only. Basically i have to create a subroutine TrimString
ID: 3743575 • Letter: M
Question
MARIE Simulator answers only. Basically i have to create a subroutine TrimString which will remove any space characters before and after a String. For example, where _ represents a blank, __MARIE__ becomes MARIE after trimming it.
The String has to be trimmed in 2 phases,
The first phase removes any trailing space (i.e., spaces at the end
of the string).
Your code should follow these steps to achieve the result:
1. Iterate through the string, one character at a time, until you reach the end of the
string (the 0 character). This is similar to how the PrintString subroutine works,
just without actually printing the characters.
2. In step 1, you found the address of the nal 0 in the string. Now iterate backwards,
and replace any space character (decimal 32) with a 0, until you reach a character
that is not a space character, or the beginning of the string.
The second phase removes leading space characters.
This approach modifies the start address of the string, up-
dating it to the rst non-space character.
1. Iterate through the string, one character at a time, until you reach a character
that is not the space character (decimal 32).
2. Update the start address of the string (at label TrimStringAddr) to the address
you found in step 1 (the address of the first non-space character).
Explanation / Answer
#!/usr/bin/perl # Taken from http://www.somacon.com/p114.php # Declare the subroutines sub trim($); sub ltrim($); sub rtrim($); # Create a test string my $string = " Hello world! "; # Here is how to output the trimmed text "Hello world!" print trim($string)." "; print ltrim($string)." "; print rtrim($string)." "; # Perl trim function to remove whitespace from the start and end of the string sub trim($) { my $string = shift; $string =~ s/^s+//; $string =~ s/s+$//; return $string; } # Left trim function to remove leading whitespace sub ltrim($) { my $string = shift; $string =~ s/^s+//; return $string; } # Right trim function to remove trailing whitespace sub rtrim($) { my $string = shift; $string =~ s/s+$//; return $string; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.