2015-08-21 178 views
2

基本问题添加到另一个字符串串

的开始,我有2个字符串。我想添加一个字符串到另一个?这里有一个例子:

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

这里我有2个字符串。我想将firstString添加到secondString,而不是反之。 (具体做法是:firstString += secondString。)

更多细节

我有5 string

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

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

我知道肯定thirdfourth将在fullString,但我不知道约firstsecond

所以我会做一个if statement检查是否second00。如果是这样,firstsecond不会进入fullString。如果不是,则为second will go into fullString`。

然后我会检查是否first00。如果是这样,那么first将不会进入fullString,如果没有,它会去。

事情是,我需要他们在相同的顺序:第一,第二,第三第四。所以在if语句中,我需要一种方法在fullString的开头添加firstsecond

+0

...你试过secondString + = firstString? – mrcheshire

+0

我更新了问题 – Horay

回答

3

回复。你的基本的问题:

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

secondString = firstString + secondString 

这里是(在secondfirst)插入开头的字符串 “不重置” 按您的评论道:

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

Re。你的“更详细”问题:

var fullString: String 

if second == "00" { 
    fullString = third + fourth 
} else if first == "00" { 
    fullString = second + third + fourth 
} else { 
    fullString = first + second + third + fourth 
} 
+0

我更新了问题 – Horay

+0

我可以这样做,但我想知道是否有办法在不重置字符串的情况下执行此操作。 – Horay

+0

查看我的最新评论。 – MirekE

3

Apple documentation

let string1 = "hello" 
let string2 = " there" 
var welcome = string1 + string2 
// welcome now equals "hello there" 

您:

字符串值可以用加法运算符(+)来创建一个新的字符串值加在一起(或连续)还可以使用加法赋值运算符(+ =)将字符串值附加到现有字符串变量:

var instruction = "look over" 
instruction += string2 
// instruction now equals "look over there" 

您可以将字符值附加到一个字符串变量,String类型的append()方法:

let exclamationMark: Character = "!" 
welcome.append(exclamationMark) 
// welcome now equals "hello there!" 

那么,你是非常自由地以任何方式形状添加这些或形成。 其中包括

secondstring += firststring 

编辑以适应新的信息: Strings in Swift are mutable这意味着你可以随时添加到就地字符串而无需重新创建任何对象。

喜欢的东西(伪代码)

if(second != "00") 
{ 
    fullstring = second + fullstring 
    //only do something with first if second != 00 
    if(first != "00") 
    { 
    fullstring = first + fullstring 
    } 
} 
+0

我更新了问题 – Horay

相关问题