How to get the first character from a word or a string - swift4

Say , I have the middlename as follows and I used below code.
var firstMiddlename = "Thompson"
let firstCharIndex = firstMiddlename.startIndex
let firstChar = firstMiddlename.index(after: firstCharIndex)
Somehow, this is not working. Please show me how to get the first character.
// update:
var firstMiddlename = "Thompson"
let firstCharacter = firstMiddlename.first
let name = MyFirstName + " " + firstCharacter + " " + MyLastName
Error:
Binary operator '+' cannot be applied to operands of type 'String' and 'Character?'
Thanks

Swift 4.x
var firstMiddlename = "Thompson"
let firstCharcter = firstMiddlename.first
print(firstCharcter) // T
And if you want to set of character from first or last. You can use prefix
firstMiddlename.prefix(2) // Th
And final append string like this
let name = "\(MyLastName) \(firstMiddlename.first!) \(MyLastName)"

Use prefix
For example:
let firstChar = firstMiddlename.prefix(1)

Related

How to trim first 3 character from a string in swift

I have a dropdown(userCphList) in which there are 2 value : 66/001/0004, 66/002/9765. I want to trim the selected value of dropdown from 66/001/0004 to 001/0004.
Given below is my code:
userCphList.didSelect{(selectedText , index ,id) in
let cphid = selectedText
let url = self.appDelegate.BaseUrl + "geojson/proj_4326?cph_id=" + cphid
self.get_wl_geojsondata(url: url)
}
I want to get cphid as 001/0004.
Any help will be highly appreciated!
Thank You!
Rutuparna Panda
You can split your string where separator is a slash, drop the first component and then join it again:
let str = "66/001/0004"
let trimmed = str.split { $0 == "/" }
.dropFirst()
.joined(separator: "/") // "001/0004"
Another option is to find the first slash index and get the substring after it:
if let index = str.firstIndex(of: "/") {
let trimmed = str[str.index(after: index)...] // "001/0004"
// or simply dropping the first character
// let trimmed = str[index...].dropFirst()
}
If the number of characters to be dropped is fixed the easiest way is dropFirst
let string = "66/001/0004"
let trimmedString = String(string.dropFirst(3))
Other ways are Regular Expression
let trimmedString = string.replacingOccurrences(of: "^\\d+/", with: "", options: .regularExpression)
and removing the substring by range
if let range = string.range(of: "/") {
let trimmedString = String(string[range.upperBound...])
}

Display of special characters \u{n}

Impossible to find the solution ; it does not work...
I've been on this for hours... A little help will give me the opportunity to sleep without a nightmare...
Where is the error ?
let num: Int = 128150 // smiley = "\u{1F496}" => 128150
var str: String = String(num, radix: 16)
str = str.uppercased()
var wkHex: String = "\\u{"+str+"}" // wkHex = "\u{"+str+"}" not match
wkHex.characters.removeFirst(0) // remove "\" unnecessary at startIndex
let cnt = wkHex.characters.count
let zzz: Array = Array(wkHex.characters)
var car: String = ""
for i in 0...cnt - 1 {
car.append(zzz[i])
}
outputChar.stringValue = car // outputChar is a Label (NSTextField)
// output : \u{1F496} ! instead of : 💖
So the idea is to go from a code point to a character?
let iii = 128150
let char = Character(UnicodeScalar(iii)!)
print(char) // 💖
Swift only allows you to use the \u{...} syntax at compile time. This means that the string won't be turned into the emoji at runtime, when the value of num is known.
To do this, you can use UnicodeScalar:
let unicode = UnicodeScalar(128150)
unicode?.description // 💖

Swift 3: How to do string ranges?

Last night I had to convert my Swift 2.3 code to Swift 3.0 and my code is a mess after the conversion.
In Swift 2.3 I had the following code:
let maxChar = 40;
let val = "some long string";
var startRange = val.startIndex;
var endRange = val.startIndex.advancedBy(maxChar, limit: val.endIndex);
let index = val.rangeOfString(" ", options: NSStringCompareOptions.BackwardsSearch , range: startRange...endRange , locale: nil)?.startIndex;
Xcode converted my code to this which doesn't work:
let maxChar = 40;
let val = "some long string";
var startRange = val.startIndex;
var endRange = val.characters.index(val.startIndex, offsetBy: maxChar, limitedBy: val.endIndex);
let index = val.range(of: " ", options: NSString.CompareOptions.backwards , range: startRange...endRange , locale: nil)?.lowerBound
The error is in the parameter range in val.rage, saying No '...' candidates produce the expected contextual result type 'Range?'.
I tried using Range(startRange...endRange) as suggestd in the docs but I'm getting en error saying: connot invoke initiliazer for type ClosedRange<_> with an arguement list of type (ClosedRange). Seems like I'm missing something fundametnal.
Any help is appreciated.
Thanks!
Simple answer: the fundamental thing you are missing is that a closed range is now different from a range. So, change startRange...endRange to startRange..<endRange.
In more detail, here's an abbreviated version of your code (without the maxChar part):
let val = "some long string";
var startRange = val.startIndex;
var endRange = val.endIndex;
let index = val.range(
of: " ", options: .backwards, range: startRange..<endRange)?.lowerBound
// 9
Now you can use that as a basis to restore your actual desired functionality.
However, if all you want to do is split the string, then reinventing the wheel is kind of silly:
let arr = "hey ho ha".characters.split(separator:" ").map{String($0)}
arr // ["hey", "ho", "ha"]

How to remove slash "/" in string in Swift

I have a string like "http://example.com/a/b/c". I want to transform the string to "httpexamplecomabc" in order to save it as the file name. I have tried
let result = str.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "//"))
and
let result = str.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "/"))
but neither works. Any Idea on how to remove "/"? Thanks
You can replace occurrence of "/ " to "" by using
let mm = "http://example.com/a/b/c"
let newString = mm.stringByReplacingOccurrencesOfString("/", withString: "")
print(newString) // http:example.comabc

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*

Categories