Swift program to compare two strings

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to compare two strings.

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 compare two string whether they are equal or not using = = operator.

Below is a demonstration of the same −

Suppose our given input is −

Str1 = "Good"
Str2 = "Good"

The desired output would be −

Yes both the stings are equal

Suppose our given input is −

Str1 = "Good"
Str2 = "bad"

The desired output would be −

No both the stings are not equal

Syntax

Following is the syntax −

Str1 == Str2

Algorithm

Following is the algorithm −

  • Step 1− Declare two string type variables.

  • Step 2− Assign values to the variables. Here the value can be pre-defined or user defined.

  • Step 3− Compare the strings using = = operator.

myStr1 == myStr2
  • Step 4− Print the output.

Example 1

The following program shows how to compare two strings.

import Foundation import Glibc var myStr1 : String var myStr2 : String myStr1 = "sky is blue" myStr2 = "sky is blue" print("String 1 =",myStr1,"
String 2 ="
,myStr2) // Comparing two strings // Using == operator if(myStr1 == myStr2){ print("YES! both the strings are equal") } else{ print("NO! both the strings are not equal") }

Output

String 1 = sky is blue
String 2 = sky is blue
YES! both the strings are equal

Here in the above code, we have two strings named myStr1 and myStr2. Now we compare them and check whether they are equal or not using = = operator. Here both the stings are equal so it will return "YES! both the strings are equal".

Example 2

The following program shows how to compare two strings.

import Foundation import Glibc var myStr1 : String var myStr2 : String // Reading string from the user myStr1 = "morning" print("String 1 =", myStr1) myStr2 = "Morning" print("String 2 = ", myStr2) // Comparing two strings // Using == operator if(myStr1 == myStr2) { print("YES! both the strings are equal") } else{ print("NO! both the strings are not equal") }

Output

String 1 = morning 
String 2 = Morning 
NO! both the strings are not equal

Here in the above code, we have two strings named myStr1 "morning" and myStr2 = "Morning". Now we compare them and check whether they are equal or not using operator. Here both the stings are not equal to each other because Swift is a case sensitive language it treated morning and Morning as a different words, so it will return NO! both the strings are not equal.

raja
Updated on 10-Oct-2022 13:00:17

Advertisements