Q:

Swift program to check a string contains a specified prefix

belongs to collection: Swift String Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swift program to check a string contains a specifi... >>
<< Swift program to print the ASCII value of characte...