How to get substring of String in Swift? [duplicate] - ios

This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
If I want to get a value from the NSString "😃hello World😃", what should I use?
The return value I want is "hello World".
The smileys can be any string. so i need some regexp to this.

There's more than one way to do it.
First: String in Swift 1.2 is bridged to NSString properly so the answer could be : How to get substring of NSString?
Second: This answer will deal with emoticon characters too.
var s = "😃hello World😃"
let index = advance(s.startIndex, 1) // index is a String.Index to the 2nd glyph, “h”
let endIndex = advance(s.startIndex, 12)
let substring=s[index..<endIndex] // here you got "hello World"
if let emojiRange = s[index...s.endIndex].rangeOfString("😃") {
let substring2 = s[index..<emojiRange.startIndex] // here you get "hello World"
}

Related

Swift - Whitespace count in a string [duplicate]

This question already has answers here:
Find number of spaces in a string in Swift
(3 answers)
Closed 5 years ago.
How do you get the count of the empty space within text?
It would be more helpful to me if explained with an example.
You can either use componentsSeparatedBy or filter function like
let array = string.components(separatedBy:" ")
let spaceCount = array.count - 1
or
let spaceCount = string.filter{$0 == " "}.count
If you want to consider other whitespace characters (not only space) use regular expression:
let string = "How to get count of the empty space in text,Like how we get character count like wise i need empty space count in a text, It would be more helpful if explained with an example."
let regex = try! NSRegularExpression(pattern: "\\s")
let numberOfWhitespaceCharacters = regex.numberOfMatches(in: string, range: NSRange(location: 0, length: string.utf16.count))
Regular expression \\s considers tab, cr, lf and space
Easiest way is to do something like this:
let emptySpacesCount = yourString.characters.filter { $0 == " " }.count
What this does is it takes characters from your string, filter out everything that is not space and then counts number of remaining elements.
You can try this example;
let string = "Whitespace count in a string swift"
let spaceCount = string.characters.filter{$0 == " "}.count

How to decode unicode characters in swift 3? [duplicate]

This question already has answers here:
Using Swift to unescape unicode characters, ie \u1234
(3 answers)
Closed 6 years ago.
I am developing one chat application, for that everything is working fine except. This application is in both Android and iOS platform. We want to pass emoji in the chat. In android we use UTF encoding with StringEscapeUtils. it is working perfect in android. when we pass emoji it is encoded and stored in DB like "\u263A".
Now in android this string is also decode and shown perfect in view but some how we can not decode the same string in iOS. We have simply try to
decode using UTF string. But still it is not working.
I have already follow this link Print unicode character from variable (swift)
Thanks in advance.
The easiest way is to use CFStringTransform like below.
let wI = NSMutableString( string: "\\u263a" )
CFStringTransform( wI, nil, "Any-Hex/Java" as NSString, true )
someUILabel.text = wI as String
You should try this:
For Example:
let charString = "263A"
if let charCode = UInt32(charString, radix: 16),let unicode = UnicodeScalar(charCode)
{
let str = String(unicode)
print(str)
}
else
{
print("invalid input")
}
If you want to Print on Label/TextField then:
let charString = "263A"
if let charCode = UInt32(charString, radix: 16),let unicode = UnicodeScalar(charCode)
{
let str = String(unicode)
CharLabel.text = str //Print on Label
CharTextField.text = str //Print on TextField
}
else
{
print("invalid input")
}

How to extract phrase from string using Range? [duplicate]

This question already has answers here:
Finding index of character in Swift String
(33 answers)
Closed 6 years ago.
This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.
I have a URL like this:
https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post
I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.
urlString.rangeOfString("#") returns Range
Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))
Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:
import Foundation
let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
fragment = url.fragment {
print(fragment)
}
// output: "global-best-time-to-post"
// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
let fragment = split.last {
print(String(fragment))
}
// output: "global-best-time-to-post"
// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
// Note that I use the index of the end of the found Range
// and the index of the end of the urlString to form the
// Range of my string
let fragment = urlString[endOctothorpe..<urlString.endIndex]
print(fragment)
}
// output: "global-best-time-to-post"
You could also use substringFromIndex
let string = "https://github.com..."
if let range = string.rangeOfString("#") {
let substring = string.substringFromIndex(range.endIndex)
}
but I'd prefer the NSURL way.
use componentsSeparatedByString method
let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")
your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase
var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)

Swift Checking if entire word is present in a string [duplicate]

This question already has answers here:
Detect whole word in NSStrings
(4 answers)
Closed 6 years ago.
What I want to do is to check if an entire word is present in a string. Let me give you an example.
let mainString = "this is a my string"
let searchString = "str"
if mainString.containsString(searchString) {
}
Here this condition will be true but I do not want this. I want it to be true when either "this" or "is" or "a" or "my" or "string" is searched in the mainString meaning I want to compare the whole word not the characters within the string. I hope I have elaborated it.
// The following method will return a string without punctuation and non-required stuff characters
Source of information : How to remove special characters from string in Swift 2?
func removeSpecialCharsFromString(mainString) -> String {
let okayChars : Set<Character> =
Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ".characters)
return String(text.characters.filter {okayChars.contains($0) })
}
let stringWithoutSpecialChars = removeSpecialCharsFromString(mainString)
// Source of info : Chris's answer on this page
let components = stringWithoutSpecialChars.componentsSeparatedByString(" ")
for component in components {
print(component)
}
You have to use a Regex like that :
NSString *pattern = #"\\str\\b";
NSRange range = [text rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
The \b at the end of the pattern do what you want, it will match only whole words.
I would recommend splitting your string into components and seeing if a component matches your string. Below is a method that uses components to check if any word matches a given search term.
func isTermInString(term:String, stringToSearch:String) -> Bool {
let components = stringToSearch.componentsSeparatedByString(" ")
for component in components {
if component == term {
return true
}
}
return false
}

Concatination of strings in Swift [duplicate]

This question already has answers here:
How do I concatenate strings in Swift?
(21 answers)
Closed 7 years ago.
I would like to get final String like below:
var urlString = "http://testurl.com/contacts=["1111111","2222222"]"
There are three strings http://testurl.com/contacts= , 1111111 and 2222222
How to concatenate these strings in Swift
var str1 = "http://testurl.com/contacts="
var str2 = "1111111"
var str3 = "2222222"
var finalString = "\(str1)[\"\(str2)\",\"\(str3)\"]"

Resources