Append String in Swift - ios

I am new to iOS. I am currently studying iOS using Objective-C and Swift.
To append a string in Objective-C I am using following code:
NSString *string1 = #"This is";
NSString *string2 = #"Swift Language";
NSString *appendString=[NSString stringWithFormat:#"%# %#",string1,string2];
NSLog(#"APPEND STRING:%#",appendString);
Anyone please guide me.

Its very simple:
For ObjC:
NSString *string1 = #"This is";
NSString *string2 = #"Swift Language";
ForSwift:
let string1 = "This is"
let string2 = "Swift Language"
For ObjC AppendString:
NSString *appendString=[NSString stringWithFormat:#"%# %#",string1,string2];
For Swift AppendString:
var appendString1 = "\(string1) \(string2)"
var appendString2 = string1+string2
Result:
print("APPEND STRING 1:\(appendString1)")
print("APPEND STRING 2:\(appendString2)")
Complete Code In Swift:
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING1:\(appendString1)")
print("APPEND STRING2:\(appendString2)")

In Swift, appending strings is as easy as:
let stringA = "this is a string"
let stringB = "this is also a string"
let stringC = stringA + stringB
Or you can use string interpolation.
let stringC = "\(stringA) \(stringB)"
Notice there will now be whitespace between them.
Note: I see the other answers are using var a lot. The strings aren't changing and therefore should be declared using let. I know this is a small exercise, but it's good to get into the habit of best practices. Especially because that's a big feature of Swift.

let string2 = " there"
var instruction = "look over"
choice 1 :
instruction += string2;
println(instruction)
choice 2:
var Str = instruction + string2;
println(Str)
ref this

Add this extension somewhere:
extension String {
mutating func addString(str: String) {
self = self + str
}
}
Then you can call it like:
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is
A lot of good Swift extensions like this are in my repo here, check them out: https://github.com/goktugyil/EZSwiftExtensions

You can simply append string
like:
var worldArg = "world is good"
worldArg += " to live";

var string1 = "This is ";
var string2 = "Swift Language";
var appendString = string1 + string2;
println("APPEND STRING: \(appendString)");

According to Swift 4 Documentation,
String values can be added together (or concatenated) with the addition operator (+) to create a new String value:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
You can also append a String value to an existing String variable with the addition assignment operator (+=):
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
You can append a Character value to a String variable with the String type’s append() method:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

> Swift2.x:
String("hello ").stringByAppendingString("world") // hello world

Strings concatenate in Swift language.
let string1 = "one"
let string2 = "two"
var concate = " (string1) (string2)"
playgroud output is "one two"

In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0
His
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")
Corrected
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")

SWIFT 2.x
let extendedURLString = urlString.stringByAppendingString("&requireslogin=true")
SWIFT 3.0
From Documentation:
"You can append a Character value to a String variable with the String type’s append() method:" so we cannot use append for Strings.
urlString += "&requireslogin=true"
"+" Operator works in both versions
let extendedURLString = urlString+"&requireslogin=true"

let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"

Related

Swift String operation not working

I am trying to read the string from a Label and remove the last character form it.
This is how I am trying:
#IBAction func del(sender: UIButton) {
let str = telephone.text!;
let newstr = str.remove(at: str.index(before: str.endIndex))
telephone.text = newstr;
}
When I run, I get an error:
"String" does not have a member named "remove"
Can someone help me figure out the problem?
Just started learning swift :(
remove(at:) mutates the receiver which must therefore be a variable
string:
var str = telephone.text!
str.remove(at: str.index(before: str.endIndex))
telephone.text = str
Alternatively use substring(to:), which returns the new string
instead of modifying the receiver:
let str = telephone.text!
let newstr = str.substring(to: str.index(before: str.endIndex))
telephone.text = newstr
remove is defined as follows:
public mutating func remove(at i: String.Index) -> Character
See the mutating modifier? That means it mutates the instance on which the method is called. In your case, the instance is str, a constant. Since constants cannot be mutated, the code does not compile.
And since remove returns the removed character,
let newstr = str.remove(at: str.index(before: str.endIndex))
here newstr will not be storing the string with the last character removed.
You should rewrite the method like this:
telephone.text!.remove(at: telephone.text!.index(before: telephone.text!.endIndex))
You can use:
let idx = str.index(before: str.endIndex) // compute the index
let s = str.substring(to: idx) // get the substring

Remove special characters from the string

I am trying to use an iOS app to dial a number. The problem is that the number is in the following format:
po placeAnnotation.mapItem.phoneNumber!
"‎+1 (832) 831-6486"
I want to get rid of some special characters and I want the following:
832-831-6486
I used the following code but it did not remove anything:
let charactersToRemove = CharacterSet(charactersIn: "()+-")
var telephone = placeAnnotation.mapItem.phoneNumber?.trimmingCharacters(in: charactersToRemove)
Any ideas?
placeAnnotation.mapItem.phoneNumber!.components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
Here you go!
I tested and works well.
If you want something similar to CharacterSet with some flexibility, this should work:
let phoneNumber = "1 (832) 831-6486"
let charsToRemove: Set<Character> = Set("()+-".characters)
let newNumberCharacters = String(phoneNumber.characters.filter { !charsToRemove.contains($0) })
print(newNumberCharacters) //prints 1 832 8316486
I know the question is already answered, but to format phone numbers in any way one could use a custom formatter like below
class PhoneNumberFormatter:Formatter
{
var numberFormat:String = "(###) ### ####"
override func string(for obj: Any?) -> String? {
if let number = obj as? NSNumber
{
var input = number as Int64
var output = numberFormat
while output.characters.contains("#")
{
if let range = output.range(of: "#", options: .backwards)
{
output = output.replacingCharacters(in: range, with: "\(input % 10)")
input /= 10
}
else
{
output.replacingOccurrences(of: "#", with: "")
}
}
return output
}
return nil
}
func string(from number:NSNumber) -> String?
{
return string(for: number)
}
}
let phoneNumberFormatter = PhoneNumberFormatter()
//Digits will be filled backwards in place of hashes. It is easy change the custom formatter in anyway
phoneNumberFormatter.numberFormat = "###-##-##-##-##"
phoneNumberFormatter.string(from: 18063783889)
Swift 3
func removeSpecialCharsFromString(_ str: String) -> String {
struct Constants {
static let validChars = Set("1234567890-".characters)
}
return String(str.characters.filter { Constants.validChars.contains($0) })
}
To Use
let str : String = "+1 (832) 831-6486"
let newStr : String = self.removeSpecialCharsFromString(str)
print(newStr)
Note: you can add validChars which you want in string after operation perform.
If you have the number and special character in String format the use following code to remove special character
let numberWithSpecialChar = "1800-180-0000"
let actulNumber = numberWithSpecialChar.components(separatedBy: CharcterSet.decimalDigit.inverted).joined()
Otherwise, If you have the characters and special character in String format the use following code to remove special character
let charactersWithSpecialChar = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!"
let actulString = charactersWithSpecialChar.components(separatedBy: CharacterSet.letters.inverted).joined(separator: " ")
NSString *str = #"(123)-456-7890";
NSLog(#"String: %#", str);
// Create character set with specified characters
NSMutableCharacterSet *characterSet =
[NSMutableCharacterSet characterSetWithCharactersInString:#"()-"];
// Build array of components using specified characters as separtors
NSArray *arrayOfComponents = [str componentsSeparatedByCharactersInSet:characterSet];
// Create string from the array components
NSString *strOutput = [arrayOfComponents componentsJoinedByString:#""];
NSLog(#"New string: %#", strOutput);

length (byte-wise) of a string in swift 2.2

How do we find out the length (byte-wise) of a string [declared String type, not NSString] in Swift 2.2?
I know one way out is to use _bridgeToObejectiveC().length
Is there any other way out?
let str: String = "Hello, World"
print(str.characters.count) // 12
let str1: String = "Hello, World"
print(str1.endIndex) // 12
let str2 = "Hello, World"
NSString(string: str2).length //12
Refer String length in Swift 1.2 and Swift 2.0 and Get the length of a String
let str: String = "Hello, World"
print(str.characters.count) // 12
let byteLength = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength)")//12
let str2: String = "你好"
print(str2.characters.count) // 2
let byteLength2 = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength2)")//12
Try this code:
Swift
let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let bytes : NSInteger = test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
NSLog("%i bytes", bytes);
Objective C
refer this link:
What is the length in bytes of a NSString?
I think type casting is another easier way to use the methods, properties of NSString class.
print((str as NSString).length)

How to take NSRange in swift?

I am very much new to swift language. I am performing some business logic which needs to take NSRange from given String.
Here is my requirement,
Given Amount = "144.44"
Need NSRange of only cent part i.e. after "."
Is there any API available for doing this?
You can do a regex-based search to find the range:
let str : NSString = "123.45"
let rng : NSRange = str.range("(?<=[.])\\d*$", options: .RegularExpressionSearch)
Regular expression "(?<=[.])\\d*$" means "zero or more digits following a dot character '.' via look-behind, all the way to the end of the string $."
If you want a substring from a given string you can use componentsSeparatedByString
Example :
var number: String = "144.44";
var numberresult= number.componentsSeparatedByString(".")
then you can get components as :
var num1: String = numberresult [0]
var num2: String = numberresult [1]
hope it help !!
Use rangeOfString and substringFromIndex:
let string = "123.45"
if let index = string.rangeOfString(".") {
let cents = string.substringFromIndex(index.endIndex)
print("\(cents)")
}
Another version that uses Swift Ranges, rather than NSRange
Define the function that returns an optional Range:
func centsRangeFromString(str: String) -> Range<String.Index>? {
let characters = str.characters
guard let dotIndex = characters.indexOf(".") else { return nil }
return Range(dotIndex.successor() ..< characters.endIndex)
}
Which you can test with:
let r = centsRangeFromString(str)
// I don't recommend force unwrapping here, but this is just an example.
let cents = str.substringWithRange(r!)

How to cast from string to int

I am trying to get the string from " src".."data-lazy-" in variable str, and it's work when i hard code it...
var str = "<h1 style=\"font-family: Helvetica\">Hello Pizza</h1><p>Tap the buttons above to see <strong>some cool stuff</strong> with <code>UIWebView</code><p><img src=\"https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg\" data-lazy-src=\"xxxxxxx\">"
str.rangeOfString(" src")?.startIndex
str.rangeOfString("data-lazy-")?.endIndex
let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 150, length: 245-150))
Result: src=\"https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg\" data-lazy-
Here, i'm trying not to hard code it...
var str = "<h1 style=\"font-family: Helvetica\">Hello Pizza</h1><p>Tap the buttons above to see <strong>some cool stuff</strong> with <code>UIWebView</code><p><img src=\"https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg\" data-lazy-src=\"xxxxxxx\">"
str.rangeOfString(" src")?.startIndex
str.rangeOfString("data-lazy-")?.endIndex
let myNSString = str as NSString
let start = str.startIndex.toInt()
let end = str.endIndex.toInt()
myNSString.substringWithRange(NSRange(location: start, length: end - start))
The code above show error message 'String.index' does not have a member named 'toInt'
My question is how could i solve this problem?
Sorry, i am a fairly new to swift programming language.
Casting is not the problem.
The method substringWithRange() accepts an argument of Range - a Swift range - and a Range can be created with arguments of type String.Index. Thus use:
// I'm ignoring optionals; this code is unsafe and thus only an example
let beg = str.rangeOfString(" src")!
let end = str.rangeOfString("data-lazy-")!
str.substringWithRange(Range(start: beg.endIndex, end: end.startIndex))
Specifically:
15> var str = "abc src=def xyz"
str: String = "abc src=def xyz"
16> var si = str.rangeOfString("src=")!
si: Range<String.Index> = { ... }
17> var ei = str.rangeOfString(" xyz")!
ei: Range<String.Index> = { ... }
18> str.substringWithRange(Range (start: si.endIndex, end: ei.startIndex))
$R3: String = "def"
Don't be confused by the word 'Index' in 'String.Index' - this is not like 'i' in s[i]. A String.Index is an opaque data type; it behaves more like a pointer (in a C-like language). A String.Index has lots to account for in the Unicode world of Swift strings.

Resources