How to get a substring from a specific character to the end of the string in swift 4?
To answer your direct question: You can search for the last
occurrence of a string and get the substring from that position:
let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
if let r = path.range(of: "/", options: .backwards) {
let imageName = String(path[r.upperBound...])
print(imageName) // 2017-07-07_21:14:52_0.jpeg
}
(Code updated for Swift 4 and later.)
But what you really want is the "last path component" of a file path.URL
has the appropriate method for that purpose:
let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
let imageName = URL(fileURLWithPath: path).lastPathComponent
print(imageName) // 2017-07-07_21:14:52_0.jpeg
How does String substring work in Swift
All of the following examples use
var str = "Hello, playground"
Swift 4
Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring
type back rather than a String
. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency.
A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that.
No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String.
let myString = String(mySubstring)
This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived.
Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc).
The following examples show how to get a substring in Swift.
Getting substrings
You can get a substring from a string by using subscripts or a number of other methods (for example, prefix
, suffix
, split
). You still need to use String.Index
and not an Int
index for the range, though. (See my other answer if you need help with that.)
Beginning of a string
You can use a subscript (note the Swift 4 one-sided range):
let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str[..<index] // Hello
or prefix
:
let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str.prefix(upTo: index) // Hello
or even easier:
let mySubstring = str.prefix(5) // Hello
End of a string
Using subscripts:
let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str[index...] // playground
or suffix
:
let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str.suffix(from: index) // playground
or even easier:
let mySubstring = str.suffix(10) // playground
Note that when using the suffix(from: index)
I had to count back from the end by using -10
. That is not necessary when just using suffix(x)
, which just takes the last x
characters of a String.
Range in a string
Again we simply use subscripts here.
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
let mySubstring = str[range] // play
Converting Substring
to String
Don't forget, when you are ready to save your substring, you should convert it to a String
so that the old string's memory can be cleaned up.
let myString = String(mySubstring)
Using an Int
index extension?
I'm hesitant to use an Int
based index extension after reading the article Strings in Swift 3 by Airspeed Velocity and Ole Begemann. Although in Swift 4, Strings are collections, the Swift team purposely hasn't used Int
indexes. It is still String.Index
. This has to do with Swift Characters being composed of varying numbers of Unicode codepoints. The actual index has to be uniquely calculated for every string.
I have to say, I hope the Swift team finds a way to abstract away String.Index
in the future. But until then, I am choosing to use their API. It helps me to remember that String manipulations are not just simple Int
index lookups.
How to get substring with specific ranges in Swift 4?
You can search for substrings using range(of:)
.
import Foundation
let greeting = "Hello there world!"
if let endIndex = greeting.range(of: "world!")?.lowerBound {
print(greeting[..<endIndex])
}
outputs:
Hello there
EDIT:
If you want to separate out the words, there's a quick-and-dirty way and a good way. The quick-and-dirty way:
import Foundation
let greeting = "Hello there world!"
let words = greeting.split(separator: " ")
print(words[1])
And here's the thorough way, which will enumerate all the words in the string no matter how they're separated:
import Foundation
let greeting = "Hello there world!"
var words: [String] = []
greeting.enumerateSubstrings(in: greeting.startIndex..<greeting.endIndex, options: .byWords) { substring, _, _, _ in
if let substring = substring {
words.append(substring)
}
}
print(words[1])
EDIT 2: And if you're just trying to get the 7th through the 11th character, you can do this:
import Foundation
let greeting = "Hello there world!"
let startIndex = greeting.index(greeting.startIndex, offsetBy: 6)
let endIndex = greeting.index(startIndex, offsetBy: 5)
print(greeting[startIndex..<endIndex])
Get the string up to a specific character
Expanding on @appzYourLife answer, the following will also trim off the whitespace characters after removing everything after the @ symbol.
import Foundation
var str = "hello, how are you @tom"
if str.contains("@") {
let endIndex = str.range(of: "@")!.lowerBound
str = str.substring(to: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
}
print(str) // Output - "hello, how are you"
UPDATE:
In response to finding the last occurance of the @
symbol in the string and removing it, here is how I would approach it:
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
//str = "hello, how are you @tom"
}
Or looking at @appzYourLife answer use range(of:options:range:locale:)
instead of literally reversing the characters
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Find the last occurrence of @
let endIndex = str.range(of: "@", options: .backwards, range: nil, locale: nil)!.lowerBound
//Get the string up to and after the @ symbol
let newStr = str.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = newStr
//str = "hello, how are you @tom"
}
As an added bonus, here is how I would approach removing every @
starting with the last and working forward:
var str = "hello, how are you @tom and @tim?"
if str.contains("@") {
while str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
}
//after while loop, str = "hello, how are you"
}
How to get All the characters before a specific character while starting from the last index in Swift5?
You can use String lastIndex(of:)
method to find the last occurrence of your slash character, get the index after that index limited by the string endIndex and get the substring from that index forward:
let str = "ABCD/EFG"
if let lastIndex = str.lastIndex(of: "/"),
let index = str.index(lastIndex, offsetBy: 1, limitedBy: str.endIndex) {
let substring = str[index...] // "EFG"
// if you need a string
let string = String(str[index...]) // "EFG"
}
or as suggested by @MartinR using string range(of:)
(this needs Foundation framework):
if let index = str.range(of: "/", options: .backwards)?.upperBound {
// ...
}
Swift : How to get the string before a certain character?
Use componentsSeparatedByString() as shown below:
var delimiter = " "
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])
Or to use your specific case:
var delimiter = " token1"
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])
Swift: How to get substring from start to last index of character
Just accessing backward
The best way is to use substringToIndex
combined to the endIndex
property and the advance
global function.
var string1 = "www.stackoverflow.com"
var index1 = advance(string1.endIndex, -4)
var substring1 = string1.substringToIndex(index1)
Looking for a string starting from the back
Use rangeOfString
and set options
to .BackwardsSearch
var string2 = "www.stackoverflow.com"
var index2 = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex
var substring2 = string2.substringToIndex(index2!)
No extensions, pure idiomatic Swift
Swift 2.0
advance
is now a part of Index
and is called advancedBy
. You do it like:
var string1 = "www.stackoverflow.com"
var index1 = string1.endIndex.advancedBy(-4)
var substring1 = string1.substringToIndex(index1)
Swift 3.0
You can't call advancedBy
on a String
because it has variable size elements. You have to use index(_, offsetBy:)
.
var string1 = "www.stackoverflow.com"
var index1 = string1.index(string1.endIndex, offsetBy: -4)
var substring1 = string1.substring(to: index1)
A lot of things have been renamed. The cases are written in camelCase, startIndex
became lowerBound
.
var string2 = "www.stackoverflow.com"
var index2 = string2.range(of: ".", options: .backwards)?.lowerBound
var substring2 = string2.substring(to: index2!)
Also, I wouldn't recommend force unwrapping index2
. You can use optional binding or map
. Personally, I prefer using map
:
var substring3 = index2.map(string2.substring(to:))
Swift 4
The Swift 3 version is still valid but now you can now use subscripts with indexes ranges:
let string1 = "www.stackoverflow.com"
let index1 = string1.index(string1.endIndex, offsetBy: -4)
let substring1 = string1[..<index1]
The second approach remains unchanged:
let string2 = "www.stackoverflow.com"
let index2 = string2.range(of: ".", options: .backwards)?.lowerBound
let substring3 = index2.map(string2.substring(to:))
How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator
You should leave one side empty, hence the name "partial range".
let newStr = str[..<index]
The same stands for partial range from operators, just leave the other side empty:
let newStr = str[index...]
Keep in mind that these range operators return a Substring
. If you want to convert it to a string, use String
's initialization function:
let newStr = String(str[..<index])
You can read more about the new substrings here.
How to remove a substring from string of particular index to some length in swift
var myString = "thisIsMyAutoGeneratedRandomString"
let ix = myString.startIndex // the index of 1st character
let ix2 = myString.index(ix, offsetBy: 8) // the index of 8th character
let ix3 = myString.index(ix, offsetBy: 26) // the index of 26th character
myString.removeSubrange(ix2...ix3)
print(myString) //thisIsMyString
Swift string after specific index
You can separate the sentence into array of words and get last word. Try this. You can replace " " with any character or string.
let fullString = "Blue Sky"
print(fullString.components(separatedBy: " ").last)//Sky
Or
if let index = fullString.firstIndex(of: " ") {
print(fullString[index...])//Sky
}
Related Topics
Animating Strings Fading In/Out in Swift
Horizontal Paging Uicollectionview with Automatic Item Size in a Vertical Stack View
Game Exits from Pause State After Resuming It from Background in Swift
Get Section Number in Custom Cell Button Action
Gmsmapview Animatetocameraposition Zoom in - Zoom Out Animation
How to Create an Image of Specific Size from Uiview
Can't Copy File from Bundle to Documents Directory in iOS
Uitextfield Starting Cursor Position Is Wrong
How to Instantiate and Load a View Controller Before Segueing to It Using Swift
How to Reuse Struct on Swift? or Is There Any Other Way
How to Set Response Data into Todayextenstion Widget
How to Download and View Images from the New Firebase Storage
Post Parameter to Sever Using Dictionary Swift
Sirikit, How to Display Response for Start Workout Intent
Swift Bridging Header File Won't Work with Use_Frameworks
Swift: Terminating with Uncaught Exception of Type Nsexception