Swift program to check a string contains a specified prefix

Here, we are going to learn how to check a string contains a specified prefix in Swift programming language?
Submitted by Nidhi, on June 11, 2021

Problem Solution:

Here, we will check a string contains a specified prefix or not using the hasPrefix() function. The hasPrefix() function returns true, if the string contains a specified prefix string otherwise it returns false.

Program/Source Code:

The source code to check a string contains a specified prefix is given below. The given program is compiled and executed successfully.

// Swift program to check a string contains 
// a specified prefix

var str = "ABCDE";

if(str.hasPrefix("AB"))
{
    print("AB is a prefix of string str");
}
else
{
    print("AB is not a prefix of string str");
}
if(str.hasPrefix("BC"))
{
    print("BC is a prefix of string str");
}
else
{
    print("BC is not a prefix of string str");
}

Output:

AB is a prefix of string str
BC is not a prefix of string str

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created a string str initialized with "ABCDE". Then we checked string str contains a specified prefix or not using the hasPrefix() function and printed the appropriate message on the console screen.

Swift String Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.