2021-01-21

Reverse Words

Write a script to reverse the order of words in the given string. The string may contain leading/trailing spaces. The string may have more than one space between words in the string. Print the result without leading/trailing spaces and there should be only one space between words.

#!/usr/bin/env tclsh
#
# Write a script to reverse the order of words in the given string. 
# The string may contain leading/trailing spaces. The string may
# have more than one space between words in the string. Print the
# result without leading/trailing spaces and there should be only
# one space between words.
#
if {$argc >= 1} {
    set orgstring [lindex $argv 0]
} elseif {$argc == 0} {
    puts "Please input a string"
    exit    
}

set theWords [regexp -all -inline {\S+} [string trim $orgstring]]
set result [lreverse $theWords]
puts "Output: [join $result " "]"

沒有留言: