7

Basic question

I have 2 strings. I want to add one string to another? Here's an example:

var secondString= "is your name."
var firstString = "Mike, "

Here I have 2 strings. I want to add firstString to secondString, NOT vice versa. (Which would be: firstString += secondString.)

More detail

I have 5 string

let first = "7898"
let second = "00"
let third = "5481"
let fourth = "4782"

var fullString = "\(third):\(fourth)"

I know for sure that third and fourth will be in fullString, but I don't know about first and second.

So I will make an if statement checking if second has 00. If it does, first and second won't go in fullString. If it doesn't, second will go intofullString`.

Then I will check if first has 00. If it does, then first won't go inside of fullString, and if not, it will go.

The thing is, I need them in the same order: first, second, third fourth. So in the if statement, I need a way to potentially add first and second at the beginning of fullString.

Horay
  • 1,388
  • 2
  • 19
  • 36

2 Answers2

10

Re. your basic question:

 secondString = "\(firstString)\(secondString)"

or

secondString = firstString + secondString

Here is a way to insert string at the beginning "without resetting" per your comment (first at front of second):

let range = second.startIndex..<second.startIndex
second.replaceRange(range, with: first)

Re. your "more detail" question:

var fullString: String

if second == "00" {
    fullString = third + fourth
} else if first == "00" {
    fullString = second + third + fourth
} else {
    fullString = first + second + third + fourth
}
MirekE
  • 11,515
  • 5
  • 35
  • 28
4

From the Apple 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!"

So you are pretty much free to add these in any way shape or form. Which includes

secondstring += firststring

Edit to accommodate the new information: Strings in Swift are mutable which means you can always add to a string in-place without recreating any objects.

Something like (pseudo-code)

if(second != "00")
{
  fullstring = second + fullstring
  //only do something with first if second != 00
  if(first != "00")
  {
   fullstring = first + fullstring
  }
}
fk2
  • 739
  • 1
  • 14
  • 30