How to split string into substrings on iOS?
You can also split a string by a substring, using NString's componentsSeparatedByString method.
Example from documentation:
NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
Split string by particular character ,iOS
NSString *str=@"Description#Data#IMG"; //is your str
NSArray *items = [str componentsSeparatedByString:@"#"]; //take the one array for split the string
NSString *str1=[items objectAtIndex:0]; //shows Description
NSString *str2=[items objectAtIndex:1]; //Shows Data
NSString *str3=[items objectAtIndex:2]; // shows IMG
Finally NSLog(@"your 3 stirs ==%@ %@ %@", str1, str2, str3);
Swift
//is your str
var str: String = "Description#Data#IMG"
let items = String.components(separatedBy: "#") //take the one array for split the string
var str1: String = items.objectAtIndex(0) //shows Description
var str2: String = items.objectAtIndex(1) //Shows Data
var str3: String = items.objectAtIndex(2) // shows IMG
option-2
let items = str.characters.split("#")
var str1: String = String(items.first!)
var str1: String = String(items.last!)
option 3
// An example string separated by commas.
let line = "apple,peach,kiwi"
// Use components() to split the string.
// ... Split on comma chars.
let parts = line.components(separatedBy: ",")
// Result has 3 strings.
print(parts.count)
print(parts)
Split a String into an array in Swift?
The Swift way is to use the global split
function, like so:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
How can split from string to array by chunks of given size
You can group your collection elements (in this case Characters) every n elements as follow:
extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < self.endIndex else { return nil }
let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
defer { start = end }
return self[start..<end]
}
}
func subSequences(of n: Int) -> [SubSequence] {
.init(unfoldSubSequences(limitedTo: n))
}
}
let numbers = "1234567"
let subSequences = numbers.subSequences(of: 2)
print(subSequences) // ["12", "34", "56", "7"]
edit/update:
If you would like to append the exceeding characters to the last group:
extension Collection {
func unfoldSubSequencesWithTail(lenght: Int) -> UnfoldSequence<SubSequence,Index> {
let n = count / lenght
var counter = 0
return sequence(state: startIndex) { start in
guard start < endIndex else { return nil }
let end = index(start, offsetBy: lenght, limitedBy: endIndex) ?? endIndex
counter += 1
if counter == n {
defer { start = endIndex }
return self[start...]
} else {
defer { start = end }
return self[start..<end]
}
}
}
func subSequencesWithTail(n: Int) -> [SubSequence] {
.init(unfoldSubSequencesWithTail(lenght: n))
}
}
let numbers = "1234567"
let subSequencesWithTail = numbers.subSequencesWithTail(n: 2)
print(subSequencesWithTail) // ["12", "34", "567"]
Split a String into an array in Swift?
The Swift way is to use the global split
function, like so:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
How to split strings into substring start with some characters in ios
I would just use rangeOfString:
to locate the next 43, take the 20 characters from there on with substringWithRange:
, and start over with the remaining substring (substringFromIndex:
).
NSString *str = @"43 01 08 43 13 01 18 FD 48 6B D1 43 01 22 02 01 02 02 F1 48 6B D1 43 02 03 03 51 03 52 75 48 6B D1 43 03 53 11 08 15 52 9D 48 6B D1 43 16 14 16 32 00 00";
NSMutableArray *substrings = [NSMutableArray array];
NSRange range = { .length = 20 };
while ((range.location = [str rangeOfString:@"43"].location) != NSNotFound
&& str.length >= range.length + range.location) {
[substrings addObject:[str substringWithRange:range]];
str = [str substringFromIndex:range.location + range.length];
}
Swift: How to split a string and then extract specific substring?
There is a solution below, it will extract any string between brackets into an array without brackets, it also gives you string without element as word as an array element:
var myString = "exampleString ( 123 ) "
//creates result array from String by separating elements by space
var result = myString.split(separator: " ")
//filters array to remove '(' and ')'
result = result.filter { $0 != "(" && $0 != ")" }
print(result)
Then if you want to build a String back from result array with string elements, do the following:
var resultString = result.joined(separator: " ")
print(resultString)
Might not be ideal, but it might be useful for you.
How to split the string from an array of strings in swift
you can use flatMap
:
let dates = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
let times = dates.flatMap({ $0.split(separator: " ").last ?? nil })
print(times)
// prints: ["05:32:30", "02:37", "05:32:50", "06:30:30"]
Related Topics
Ios:Retrieve Rectangle Shaped Image from the Background Image
Fbsdkaccesstoken Currentaccesstoken Nil After Quitting App
What Impact Does Simulated Metrics Have
How to Logout User Using Facebook Authentication Using Swift and iOS
Various Itms Errors When Trying to Submit Archive to App Store
Aes/Cbc/Pkcs5Padding in iOS Objective C Result Differs from Android
Xcode 6 Gm - Cllocationmanager
How to Use Call Directory Extension to Identify a Incoming Call in My Application
Custom Class Clusters in Swift
How to Determine the True Data Type of an Nsnumber
Memory Leak Every Time Uiscrollview Is Released
Firebase Limit on the Number of Observers/Listeners
Create and Perform Segue Without Storyboards
iOS - Swift - Function That Returns Asynchronously Retrieved Value
Images Not Showing Up When Architecture Set to 64 Bit
How to Convert an Int to a Character in Swift
How Come I Can Cast to Nsmanagedobject But Not to My Entity's Type