Swift Program to trim a string from the right side


In Swift, we can adjust the size of the string by trimming some specified number of characters from the right-hand side of the given string. Or we can also trim the extra whitespaces which we do not want on the right-hand side of the given string using the following methods −

Method 1: Trim a string from the right side

To trim a specified number of characters or a substring from the right side of the string we create a user-defined function which takes an input string and the length of the characters which we wanted to remove from the right-hand side of the input string as arguments and return a resultant new string.

Example

Input: String = "Ram got first place" trimLength = 5
Output: "Ram got first "

Here, in the resultant string, the last 5 characters are removed from the end of the string because the size of trimLength is 5.

Algorithm

  • Step 1 − Create a function that takes an input string and trimLength as arguments.

  • Step 2 − Now this function first checks if the trimLength is greater than or equal to the size of the input string. If yes, then return the original string.

  • Step 3 − If no, then it will use the index() function to find the new index which is “trimeLength” characters to the left of the string’s endIndex.

  • Step 4 − Then it creates a new string including all the characters starting from the first index till the new index using the range operator.

  • Step 5 − Return the new resultant string.

  • Step 6 − Create a string.

  • Step 7 − Create a variable and store the length which we want to remove from the right-hand side of the entered string.

  • Step 8 − Call the function and pass string and trimLength as arguments in it.

  • Step 9 − Display output.

Example

In the following Swift program, we will trim the string from the right side. So we create a function which takes a string and the length which we want to trim from the right side as arguments. Then it will check if the trimlength is greater than or equal to the length of the string. If yes, then it does not trim the string, and return the original string. If not, then the function calculates the index from which we want to trim using the index() function. Then use String() initializer along with partialRangeUpTo parameter([..<Index]) to create a substring from the original string up to the calculated trimIndex. Finally, display the updated string.

import Foundation
import Glibc

func trimRightString(str: String, trimlength: Int)-> String{
   if trimlength >= str.count
   {
      return str
   }
   
   let trimIndex = str.index(str.endIndex, offsetBy: -trimlength)
   let newStr = String(str[..<trimIndex])
    
   return newStr
}

let s = "Ram likes Swift"
let result = trimRightString(str: s, trimlength: 9)
print("Original String:", s)
print("String after trimming(right-hand side):", result)

Output

Original String: Ram likes Swift
String after trimming(right-hand side): Ram li

Method 2: Trim WhiteSapces from the right side

In Swift, we can also remove whitespaces from the right side of the input string. So for that, we create a user-defined function which will take the input string as an argument and return a new string which does not contain whitespaces on the right side.

Example

Input: String = "Ram got first place  "
           
Output: "Ram got first place"

Here, the input string contains two white spaces on the right so using the function we create a new string which doesn't have white spaces on the right side.

Algorithm

  • Step 1 − Create a function that takes an input string as an argument.

  • Step 2 − Now this function first calculates the last index using the endIndex property.

  • Step 3 − Then run a while loop which iterates backwards from the end of the string until it reaches the first non-whitespace character.

  • Step 4 − Creates a new string including all the characters starting from the first index to the new index using the range operator.

  • Step 5 − Return the new resultant string.

  • Step 6 − Create a string.

  • Step 7 − Call the function and pass the input string as arguments in it.

  • Step 8 − Display output.

Example

In the following Swift program, we will trim white spaces from the right. So we create a function which takes a string as an argument. Then it calculates the last index of the input string. After that, it will run a while loop which iterates backwards from the end of the string until it reaches the first non-whitespace character. Then it uses String() initializer along with partialRangeUpTo parameter([..<Index]) to create a new string that contains characters only from the start to the calculated eIndex from the original string. Finally, display the updated string.

import Foundation
import Glibc

func trimString(iStr: String) -> String {
   var eIndex = iStr.endIndex
   while eIndex > iStr.startIndex && iStr[iStr.index(before: eIndex)].isWhitespace {
      eIndex = iStr.index(before: eIndex)
   }
   let newStr = String(iStr[..<eIndex])
   return newStr
}

let oString = "   Execute Swift Program   "

let resString = trimString(iStr:oString)

print("Original string: \"\(oString)\"")
print("Trimmed string: \"\(resString)\"")

Output

Original string: "   Execute Swift Program   "
Trimmed string: "   Execute Swift Program"

Conclusion

So this is how we can trim a string from the right side. If you want to remove a string from the right-hand side of the entered string then you can use method 1. Or if you only want to remove white spaces from the right-hand side of the entered string, then you can use method 2. Both methods work effectively and trim some characters from the right of the input string either whitespace characters or non-whitespace characters.

Updated on: 16-Jun-2023

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements