How to Swap Pair of Characters in Swift?


Swapping pair of characters is a process of interchanging the position of two characters in the given string. This operation is commonly used in various programming languages and applications to manipulate data.

Example

Input

“mumbai”

Output

umbmia

Input

“Prita”

Output

rPtia

Here, we divide the given string into a pair of characters like “mumbai”: “mu”, “mb”, “ai”. Now we swap the positions of the characters: “um”, “bm”, and “ia” and create the resultant string: “umbmia”. Similarly for input 2.

In Swift, we can swap the pair of characters present in the given string using the following methods:

  • By converting into an Array

  • Using index

Method 1: Swapping Pairs by Converting into an Array

To swap pair of characters in the given string we first convert the given string to an array using Array() initializer and then swap the position of the pairs and then convert back into the string using the String() initializer.

Algorithm

Step 1 − Create a function to swap pair of characters.

Step 2 − Inside the function, we convert the string into an array of characters.

Step 3 − Run a for−in loop with the stride() function to iterate through two characters at a time and swap their positions.

Step 4 − Now convert the final array back into the string.

Step 5 − Return the resultant string.

Step 6 − Create a test string.

Step 7 − Now call the function and pass the test string into it.

Step 8 − Display the output.

Example

In the following Swift program, we will swap the pair of characters. So for that, we create a function named swappingPairsOfCharacters(). This function takes the input string as a parameter and then converts the input string into an array of characters using an Array() initializer. Then it iterates through two characters at a time and swaps their positions using swapAt() function. After completing the iteration the final array converts back into the string using String() initializer.

import Foundation
import Glibc

// Function to swap pair of characters
func swappingPairsOfCharacters(inputString: String)-> String{
    var charArray = Array(inputString)
    
    for x in stride(from: 0, to: charArray.count-1, by: 2){
        charArray.swapAt(x, x+1)
    }
    return String(charArray)
}

// Input string
let enterString: String = "Mohina"

// Calling the function
let resultantString = swappingPairsOfCharacters(inputString: enterString)

// Displaying the result
print("Original String:", enterString)
print("String after swapping pair of characters:", resultantString)

Output

Original String: Mohina
String after swapping pair of characters: oMihan

Method 2: Swapping Pairs Using index

In this method, we will swap pairs of characters with the help of their index value. Here we find the index of characters using various methods and properties like index(), startIndex, endIndex, etc. And then append the result to the new string.

Algorithm

Step 1 − Create a function to swap pair of characters.

Step 2 − Inside the function, we create an empty string to store the resultant string and a variable to keep track of the current position in the given string.

Step 3 − Then iterate through each index of the character present in the given string.

Step 4 − Inside the loop, we find the next index of the character using the index() method. If the next character is within the bounds then the loop proceeds with swapping characters and then adding swapped characters into the resultant string.

Step 5 − Finally return the resultant string.

Step 6 − Create a test string.

Step 7 − Now call the function and pass the test string into it.

Step 8 − Display the output.

Example

In the following Swift program, we will swap the pair of characters. So for that, we create a function named swapPairsOfCharacters(). This function takes the input string as a parameter and then it iterates through each character of the string. Inside the loop, we first find the next index using the index() function where we also check if the next index is inside the given bound or not, if yes then the loop proceeds to swap the characters. It extracts two characters to swap and then append the second character first in the resultant string followed by the first character using the append() function. If the next character is beyond the end of the input string, then the loop appends the last character as it is at the end of the resultant string. And finally, return the resultant string.

import Foundation
import Glibc

// Function to swap pair of characters
func swapPairsOfCharacters(inputString: String) -> String {

    var resultString = ""
    var iIndex = inputString.startIndex
    
    while iIndex < inputString.endIndex {
    
        let nextIndex = inputString.index(iIndex, offsetBy: 1, limitedBy: inputString.endIndex) ?? inputString.endIndex
        
        if nextIndex < inputString.endIndex {
            let firstChar = inputString[iIndex]
            let secondChar = inputString[nextIndex]
            
            resultString.append(secondChar)
            resultString.append(firstChar)
        } else {
            
            resultString.append(inputString[iIndex])
        }
        
        iIndex = inputString.index(iIndex, offsetBy: 2, limitedBy: inputString.endIndex) ?? inputString.endIndex
    }
    return resultString
}

// Input String
let testString = "Mumbai"

// Function calling
let resString = swapPairsOfCharacters(inputString: testString)

print("Original String:", testString)
print("String after swapping pair of characters:", resString)

Output

Original String: Mumbai
String after swapping pair of characters: uMbmia

Real− life Usage

The real−life usage of swap pair of characters is:

  • It can be used in data augmentation in natural language to create variation of text data for training machine.

  • It can also be used in steganography to hide messages inside non−secret data.

  • It can also be used as a mechanic in text−based games or puzzles.

  • Some string manipulation algorithms also use swapping pair of characters.

Conclusion

So this is how we can swap pair of characters. This swapping is useful for encryption and decryption, text transformation, data encoding, algorithm development, string anagram detection, etc. You can use any of the above following methods to swap the pair of characters present in the string.

Updated on: 08-Sep-2023

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements