Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add string to beginning of another string

Tags:

string

ios

swift

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.

like image 789
Horay Avatar asked Aug 21 '15 23:08

Horay


People also ask

How do you add a string at the beginning of another string?

Get the both strings, suppose we have a string str1 and the string to be added at begin of str1 is str2. Create an empty StringBuffer object. Initially, append str2 to the above created StringBuffer object, using the append() method, Then, append str1.

How do I add to the beginning of a string in Python?

Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.

How do you add strings to a string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.


1 Answers

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
}
like image 195
MirekE Avatar answered Sep 21 '22 01:09

MirekE