在另一个字符串的开头添加字符串

7

基本问题

我有两个字符串。我想把一个字符串加到另一个字符串上。这是一个例子:

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

这里有两个字符串。我想把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语句来检查second是否有00。如果有,则firstsecond将不会被添加到fullString中。如果没有,则second将会被添加进去。
然后我会检查first是否有00。如果有,first将不会被添加进fullString中;如果没有,它将被添加进去。
问题是,我需要他们按照同样的顺序:first, second, third, fourth。因此,在if语句中,我需要一种方法来潜在地将firstsecond添加到fullString的开头。

你尝试过 secondString += firstString 吗? - mrcheshire
我更新了问题。 - Horay
2个回答

10

关于你的基本问题:

 secondString = "\(firstString)\(secondString)"
或者
secondString = firstString + secondString

根据您的评论,这里提供一种在字符串开头插入内容的方法,同时保持原有字符串不变(将first插入到second的前面):

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

关于您的“更详细”的问题:

var fullString: String

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

我可以做到,但我想知道是否有一种不重置字符串的方法。 - Horay
请查看我的最新评论。 - MirekE
谢谢!我尝试了4个if语句,但仍然无法得到正确的结果! - Horay

4
Apple文档中得知:
字符串值可以通过加号(+)进行拼接,创建一个新的字符串值:
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

编辑以适应新信息: Swift字符串是可变的,这意味着您可以始终原地添加字符串而不必重新创建任何对象。
类似以下伪代码:
if(second != "00")
{
  fullstring = second + fullstring
  //only do something with first if second != 00
  if(first != "00")
  {
   fullstring = first + fullstring
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接