Swift program to reverse a string

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to reverse a string.

A string is an ordered set of characters, for example, "SwiftCourse" It is used to represent textual data. Swift support a String data type which is used to create a string type variable, or we can say to represent strings.

Syntax

  • Following is the syntax to create string −

var mystr : String = “My String” 
Or 
var mystr = “ My string”

In Swift, we can reverse a string without using a library function. So to reverse a string we iterate though the given string and add each character of the string to the empty string.

Below is a demonstration of the same −

Input

Suppose our given input is −

String = Sea is blue

Output

The desired output would be −

Reversed string = eulb si aeS

Algorithm

Following is the algorithm −

  • Step 1− Declare a variable of String type. Here the value of this variable can be pre-defined or user defined.

  • Step 2− Create an empty string.

  • Step 3− Use for loop to iterate through each character and then add character to the empty string to find a reversed string.

for c in myStr { 
   reverseStr = "\(c)" + reverseStr
}
  • Step 4− Print the output.

Example

The following program shows how to reverse a string.

import Foundation import Glibc // Reading string from user print("Hey user! enter a string:") var myStr = "Good" // Creating an empty string to store result var reverseStr = "" print("Original String: ", myStr) // Loop through each character // in the given string for c in myStr { reverseStr = "\(c)" + reverseStr } print("Reverse String: ", reverseStr)

Output

Hey user! enter a string:
Original String:  Good
Reverse String:  dooG

Here in the above code, we have a string = "Good".

Here in the above code, we have a string = "Good". Now we reverse this string by adding each character to the new empty string −

for c in myStr{
   reverseStr ""\( reverseStr
}

So the working of the above code is −

myStr = "Good"
reverseStr = ""
1st iteration:
for c in myStr{
   reverseStr = "\(G)" + "" = G
}   
2nd iteration:
for c in myStr{
   reverseStr = "\(o)" + "" = oG
}
3rd iteration:
for c in myStr{
   reverseStr = "\(o)" + "" = ooG
}   
4th iteration:
for c in myStr{
   reverseStr = "\(d)" + "" = dooG
}   

Hence the reversed string is dooG.

raja
Updated on 10-Oct-2022 12:50:57

Advertisements