Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Last active March 27, 2019 22:43
Show Gist options
  • Select an option

  • Save topherPedersen/560a4f4bf945543ad420b6048266033b to your computer and use it in GitHub Desktop.

Select an option

Save topherPedersen/560a4f4bf945543ad420b6048266033b to your computer and use it in GitHub Desktop.
String Reversal Tool (Assignment) in Swift by Jonathan S
/*
REFERENCE: Text Based Interface in Swift
print("Enter text here> ")
var userInput = readLine()!
print("User entered: \(userInput)")
*/
// Jonathan, make me a string reversal script in Swift (please)
// Step 1: Greet the user (Jonathan's String Reversal Tool)
// Step 2: Prompt the user to enter a string to be reversed
// Step 3: Create a new empty string
// Step 4:
print("Welcome to Jonathan's String Reversal Tool!")
print("Enter a phrase and have it reversed> ")
var userInput = readLine()!
// Jonathan, we need to make a second (empty) string
// We will put the characters from the old string
// into the new string, to build the 'reversed string'
// We will accomplish this using the loop we created
// below, that happens to count backwards.
// The first time the loop runs, the last letter
// of the userInput string will be represented as
// userInput[i], therefore we can add this last
// letter to our new string. We will continue
// doing this, as we loop backwards through the
// userInput string.
// userInput[i]
// REFERENCE (get char in swift): https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language
// var firstChar = Array(string)[0]
var myNewString: String = ""
var i = userInput.count
while i <= userInput.count && i > 0 {
i = i - 1
let myChar = Array(userInput)[i]
/*
print(myChar)
*/
// Jonathan, You need to create a new (empty) string OUTSIDE
// of this loop. THEN, inside this loop, add the new character (myChar)
// to your new string. Go!
// Hint, write your code here Jonathan...
myNewString = myNewString + String(myChar)
}
print(myNewString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment