Difference between revisions of "W1116 String Functions"

From Coder Merlin
m (Editorial review and minor corrections)
 
Line 1: Line 1:
{{MerlinNoteFromEditor|I think Swift is an established language now. Please review the statements below stating that it's a "new" language and, in the second paragraph, that it's not fully released. Revise to be more timeless. Maybe something like: ...language features can change in new releases, so the examples might become inaccurate.?}}
Swift is a new programming language developed by Apple for use with iOS and OS X development. One of the things that makes Swift so unique is its focus on safety. Because of this, it doesn't have as many functions as Objective-C, but those that it does have are more powerful. This article highlights some of those string functions from Apple's API documentation for String.
Swift is a new programming language developed by Apple for use with iOS and OS X development. One of the things that makes Swift so unique is its focus on safety. Because of this, it doesn't have as many functions as Objective-C, but those that it does have are more powerful. This article highlights some of those string functions from Apple's API documentation for String.


Line 6: Line 7:
{{MerlinCurriculumData|{{ROOTPAGENAME}}}}
{{MerlinCurriculumData|{{ROOTPAGENAME}}}}


You can concatenate strings in Swift with the addition operator (+). In its most basic form, you can simply add two strings together to make one string:
You can concatenate strings in Swift by using the addition operator (+). In its most basic form, you can simply add two strings together to make one string:


<syntaxhighlight lang="swift"> let myString = "I am" + " awesome." //myString is equal to "I am awesome." </syntaxhighlight>
<syntaxhighlight lang="swift"> let myString = "I am" + " awesome." //myString is equal to "I am awesome." </syntaxhighlight>


This is nice and simple but it's not extremely useful. What if you want to take a string and add some numbers? Or what if you have multiple parts to your string that need concatenating together? Well for this Swift has provided an alternative, named concatenation operator (&+). This works much like the addition operator except instead of appending the second operand (the number corresponding to String ) to the end of the first operand (the string), it will create a new string out of the two.
This is nice and simple, but it's not extremely useful. What if you want to take a string and add some numbers? Or what if you have multiple parts to your string that you want to concatenate? For these cases, Swift provides an alternative called the concatenation operator (&+). This works much like the addition operator except instead of appending the second operand (the number corresponding to String) to the end of the first operand (the string), it creates a new string out of the two.


There is no limit to how many strings you can concatenate in this way, so it only makes sense that there are functions that are similar to the addition (+) and concatenation (&+) operators, called string-append and string-insert. These work on any number of strings at once, appending them together on an element-by-element basis.  
There is no limit to how many strings you can concatenate in this way, so it only makes sense that there are functions that are similar to the addition (+) and concatenation (&+) operators, called string-append and string-insert. These work on any number of strings at once, appending them together element by element.


{{CodeExplorer
{{CodeExplorer
Line 26: Line 27:
== String Comparisons ==
== String Comparisons ==


Swift also provides functions for determining the equality between two strings, checking if one string is greater than another and also checking if one exists in another. These are useful when you want to make sure that user input matches up with what your application expects.
Swift also provides functions for determining the equality between two strings, checking if one string is greater than another and checking if one exists in another. These are useful when you want to make sure that user input matches up with what your application expects.


String comparisons in Swift are made with the case-sensitive equal to the operator (==), the not equal to operator (!=), and using ranges with the contains property.
String comparisons in Swift are made with the case-sensitive ''equal to'' operator (==), the ''not equal to'' operator (!=), and using ranges with the ''contains'' property.


Here are some examples of what these operators do:
Here are some examples of what these operators do:
Line 50: Line 51:


== Accessing Characters by Index ==
== Accessing Characters by Index ==
You can access individual characters in a String using the index of the character, with indexes starting from 0. This is done with a method called <syntaxhighlight lang="swift" inline> charAt(index:) </syntaxhighlight>
You can access individual characters in a String using the index of the character, with indexes starting from 0. We do this by using a method called <syntaxhighlight lang="swift" inline> charAt(index:) </syntaxhighlight>


This method returns a single Character object, so bear that in mind if you need to do any sort of comparisons on it--it won't be a simple boolean value. An example of this is as follows:
This method returns a single Character object. So bear that in mind if you need to do any sort of comparisons on it, it won't be a simple Boolean value. An example of this is as follows:


{{CodeExplorer
{{CodeExplorer
Line 81: Line 82:
}}
}}


Remember that when you do this, it will include all punctuation and extra whitespace.
Remember that when you do this, it includes all punctuation and extra white space.


== Finding Position of Substring Within a String ==
== Finding the Position of Substring within a String ==


You can use the index of a string to search for the position of another string inside it. This is done with the <syntaxhighlight lang="swift" inline>range(of:)</syntaxhighlight> method which returns an optional integer, with nil meaning that the substring was not found.
You can use the index of a string to search for the position of another string inside it. Do this by using the <syntaxhighlight lang="swift" inline>range(of:)</syntaxhighlight> method, which returns an optional integer. If it returns nil, it means that the substring was not found.


This method can be very useful when you want to find out where a string occurs in another string. It will also let you know if it was not found in the string, which can be important.
This method can be very useful when you want to find out where a string occurs in another string. It also lets you know if it was not found in the string, which can be important.


== Appending Strings Together ==
== Appending Strings Together ==
Line 93: Line 94:
Swift provides three methods for appending strings together: <syntaxhighlight lang="swift" inline> append(string), appendContentsOf(_:) and join()</syntaxhighlight>
Swift provides three methods for appending strings together: <syntaxhighlight lang="swift" inline> append(string), appendContentsOf(_:) and join()</syntaxhighlight>


The first method, append(string), will simply add another String to the end of the receiver String. Like with concatenation, this method takes one string as an argument.
The first method, append(string), simply adds another String to the end of the receiver String. Like with concatenation, this method takes one string as an argument.


Here's how it is used:
Here's how it is used:
Line 110: Line 111:
The second two methods are similar to the first, taking a function with a String type as its sole argument.
The second two methods are similar to the first, taking a function with a String type as its sole argument.


The difference is that the first argument to these functions is another String, which will be added to the receiver string. For example:
The difference is that the first argument to these functions is another String, which is added to the receiver string. For example:


{{CodeExplorer
{{CodeExplorer
Line 125: Line 126:




While this may seem like an unnecessary repetition of effort, it can make your code easier to read by not having to reference your constant string variable constantly.
Although this might seem like an unnecessary repetition of effort, it can make your code easier to read by not having to reference your constant string variable constantly.


== Inserting Strings into Other Strings ==
== Inserting Strings into Other Strings ==


You can insert a String into another String using the (insert:) method. This inserts the string to be inserted anywhere in the receiver string and inserts nothing if the insertion point is outside of its limits.
You can insert a String into another String using the (insert:) method. This inserts the string to be placed anywhere in the receiver string and inserts nothing if the insertion point is outside of its limits.


Here's an example:
Here's an example:
Line 144: Line 145:
}}
}}


Note that this doesn't have any effect on the length of the string--it does not grow to accommodate itself. It also takes an optional argument atIndex: which specifies where in the receiver String it should be inserted. If you omit the argument, it finds its own insertion point by looking at the beginning or end of the string.
Note that this doesn't have any effect on the length of the string—it does not grow to accommodate itself. It also takes an optional argument atIndex:, which specifies where in the receiver String it should be inserted. If you omit the argument, it finds its own insertion point by looking at the beginning or end of the string.


== Replacing Substrings in Strings ==
== Replacing Substrings in Strings ==
Line 161: Line 162:
}}
}}


This method will replace all occurrences of the string in the argument with another string in its receiver. This is very useful if you want to replace certain terms (or even misspellings) in your code, but only one at a time.
This method replaces all occurrences of the string in the argument with another string in its receiver. This is very useful if you want to replace certain terms (or even misspellings) in your code, but only one at a time.


== Removing Substrings from Strings ==
== Removing Substrings from Strings ==
Line 181: Line 182:
With this method, unlike the (replacingOccurrencesOf:) method, you must specify where in the string it should be removed. Also note that if you remove a substring that doesn't exist in the string, this method does nothing.
With this method, unlike the (replacingOccurrencesOf:) method, you must specify where in the string it should be removed. Also note that if you remove a substring that doesn't exist in the string, this method does nothing.


You can remove an entire String from a string using the (removingRangeOfString:) method. This also takes a String as its argument, but then deletes that string from the receiver string wherever it appears, and then returns a new string with the deleted contents.
You can remove an entire String from a string using the (removingRangeOfString:) method. This also takes a String as its argument, but then it deletes that string from the receiver string wherever it appears, and then returns a new string with the deleted contents.


== Changing Cases ==
== Changing Cases ==
Line 187: Line 188:
You can change the case of a string by using its <syntaxhighlight lang="swift" inline >(lowercaseString)
You can change the case of a string by using its <syntaxhighlight lang="swift" inline >(lowercaseString)
</syntaxhighlight>
</syntaxhighlight>
or  <syntaxhighlight lang="swift" inline >(uppercaseString) </syntaxhighlight>properties. These return another String, with the receiver's contents in lower- or uppercase respectively.
or  <syntaxhighlight lang="swift" inline >(uppercaseString) </syntaxhighlight>properties. These return another String, with the receiver's contents in lowercase or uppercase, respectively.


For example:  
For example:  
Line 207: Line 208:
}}
}}


These two properties can be useful for things like converting user input or capitalizing words in a sentence. They do not mutate the original string; instead, they return a new one.  
These two properties can be useful for things like converting user input or capitalizing words in a sentence. They do not modify the original string; instead, they return a new one.  


== Conclusion ==
== Conclusion ==


String functions in Swift are very useful and can help you get a lot of work done with little effort. It's good to become familiar with all of these methods, particularly the ones that remove portions of strings. That way, you can quickly get the contents you want without needing to create a whole new string. String functions are also useful if you need to change certain words in your code depending on context- for example, turning "item" into "items."
String functions in Swift are very useful and can help you get a lot of work done with little effort. It's good to become familiar with all of these methods, especially the ones that remove portions of strings. This way, you can quickly get the contents you want without needing to create a whole new string. String functions are also useful if you need to change certain words in your code depending on context—for example, turning "item" into "items."


The thing to take away is that  Swift is a very versatile language. Most of the functions that are available in Objective-C are also available here, just with different syntax and functionality. String functions are one example of this, but there are many others as well.
The thing to take away is that  Swift is a very versatile language. Most of the functions that are available in Objective-C are also available here, just with different syntax and functionality. String functions are one example of this, but there are many others as well.

Latest revision as of 09:39, 11 February 2023

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

 This article can be improved by:  I think Swift is an established language now. Please review the statements below stating that it's a "new" language and, in the second paragraph, that it's not fully released. Revise to be more timeless. Maybe something like: ...language features can change in new releases, so the examples might become inaccurate.?

Swift is a new programming language developed by Apple for use with iOS and OS X development. One of the things that makes Swift so unique is its focus on safety. Because of this, it doesn't have as many functions as Objective-C, but those that it does have are more powerful. This article highlights some of those string functions from Apple's API documentation for String.

You must remember, however, that the language itself is not fully released and so this article, and the corresponding code examples may change in future releases of Swift.

Curriculum[edit]

ExercisesIcon.png
 Coder Merlin™  Computer Science Curriculum Data

Unit:

Experience Name: W1116 String Functions ()

Next Experience: ()

Knowledge and skills: noneSome use of "" in your query was not closed by a matching "".

Topic areas: none

Classroom time (average):

Study time (average):

Successful completion requires knowledge: none

Successful completion requires skills: none

You can concatenate strings in Swift by using the addition operator (+). In its most basic form, you can simply add two strings together to make one string:

 let myString = "I am" + " awesome." //myString is equal to "I am awesome."

This is nice and simple, but it's not extremely useful. What if you want to take a string and add some numbers? Or what if you have multiple parts to your string that you want to concatenate? For these cases, Swift provides an alternative called the concatenation operator (&+). This works much like the addition operator except instead of appending the second operand (the number corresponding to String) to the end of the first operand (the string), it creates a new string out of the two.

There is no limit to how many strings you can concatenate in this way, so it only makes sense that there are functions that are similar to the addition (+) and concatenation (&+) operators, called string-append and string-insert. These work on any number of strings at once, appending them together element by element.

CoderMerlin™ Code Explorer: W0000 (1) 🟢


String Comparisons[edit]

Swift also provides functions for determining the equality between two strings, checking if one string is greater than another and checking if one exists in another. These are useful when you want to make sure that user input matches up with what your application expects.

String comparisons in Swift are made with the case-sensitive equal to operator (==), the not equal to operator (!=), and using ranges with the contains property.

Here are some examples of what these operators do:

CoderMerlin™ Code Explorer: W0000 (2) 🟢


Accessing Characters by Index[edit]

You can access individual characters in a String using the index of the character, with indexes starting from 0. We do this by using a method called charAt(index:)

This method returns a single Character object. So bear that in mind if you need to do any sort of comparisons on it, it won't be a simple Boolean value. An example of this is as follows:

CoderMerlin™ Code Explorer: W0000 (3) 🟢


Accessing String Length[edit]

You can get the length of a String by using its length property. This is simply an integer, not an actual character count (it includes all spaces and punctuation too). Here's an example:

CoderMerlin™ Code Explorer: W0000 (4) 🟢


Remember that when you do this, it includes all punctuation and extra white space.

Finding the Position of Substring within a String[edit]

You can use the index of a string to search for the position of another string inside it. Do this by using the range(of:) method, which returns an optional integer. If it returns nil, it means that the substring was not found.

This method can be very useful when you want to find out where a string occurs in another string. It also lets you know if it was not found in the string, which can be important.

Appending Strings Together[edit]

Swift provides three methods for appending strings together: append(string), appendContentsOf(_:) and join()

The first method, append(string), simply adds another String to the end of the receiver String. Like with concatenation, this method takes one string as an argument.

Here's how it is used:

CoderMerlin™ Code Explorer: W0000 (5) 🟢


The second two methods are similar to the first, taking a function with a String type as its sole argument.

The difference is that the first argument to these functions is another String, which is added to the receiver string. For example:

CoderMerlin™ Code Explorer: W0000 (6) 🟢


Although this might seem like an unnecessary repetition of effort, it can make your code easier to read by not having to reference your constant string variable constantly.

Inserting Strings into Other Strings[edit]

You can insert a String into another String using the (insert:) method. This inserts the string to be placed anywhere in the receiver string and inserts nothing if the insertion point is outside of its limits.

Here's an example:

CoderMerlin™ Code Explorer: W0000 (7) 🟢


Note that this doesn't have any effect on the length of the string—it does not grow to accommodate itself. It also takes an optional argument atIndex:, which specifies where in the receiver String it should be inserted. If you omit the argument, it finds its own insertion point by looking at the beginning or end of the string.

Replacing Substrings in Strings[edit]

You can replace all occurrences of a substring inside a string with another String using the (replacingOccurrencesOf:) method. This method is very useful when you need to make multiple changes in one go. Here's an example:

CoderMerlin™ Code Explorer: W0000 (8) 🟢


This method replaces all occurrences of the string in the argument with another string in its receiver. This is very useful if you want to replace certain terms (or even misspellings) in your code, but only one at a time.

Removing Substrings from Strings[edit]

You can remove a substring from a string by using the (removingSubrangeOfString:) method. This takes a String as an argument and then deletes that string from the receiver string, wherever it appears. For example:

CoderMerlin™ Code Explorer: W0000 (9) 🟢


With this method, unlike the (replacingOccurrencesOf:) method, you must specify where in the string it should be removed. Also note that if you remove a substring that doesn't exist in the string, this method does nothing.

You can remove an entire String from a string using the (removingRangeOfString:) method. This also takes a String as its argument, but then it deletes that string from the receiver string wherever it appears, and then returns a new string with the deleted contents.

Changing Cases[edit]

You can change the case of a string by using its (lowercaseString) or (uppercaseString)properties. These return another String, with the receiver's contents in lowercase or uppercase, respectively.

For example:

CoderMerlin™ Code Explorer: W0000 (10) 🟢


These two properties can be useful for things like converting user input or capitalizing words in a sentence. They do not modify the original string; instead, they return a new one.

Conclusion[edit]

String functions in Swift are very useful and can help you get a lot of work done with little effort. It's good to become familiar with all of these methods, especially the ones that remove portions of strings. This way, you can quickly get the contents you want without needing to create a whole new string. String functions are also useful if you need to change certain words in your code depending on context—for example, turning "item" into "items."

The thing to take away is that Swift is a very versatile language. Most of the functions that are available in Objective-C are also available here, just with different syntax and functionality. String functions are one example of this, but there are many others as well.