ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.