Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 3大写字符串_Swift_String - Fatal编程技术网

Swift 3大写字符串

Swift 3大写字符串,swift,string,Swift,String,我试图将第一个和第三个字符大写,然后将所有3个字符合并成一个新字符串 但是.uppercase和.capitalized不起作用 另外,如何检查第二个字符是否是数字?。大写的和。大写的仅适用于字符串,您显示的是字符s。您可以将字符转换为字符串,并将其大写 let first = postalText.text?[(postalText.text?.startIndex)!] let second = postalText.text?[(postalText.text?.index

我试图将第一个和第三个字符大写,然后将所有3个字符合并成一个新字符串 但是.uppercase和.capitalized不起作用


另外,如何检查第二个字符是否是数字?

。大写的
。大写的
仅适用于字符串,您显示的是
字符
s。您可以将
字符
转换为
字符串
,并将其大写

    let first = postalText.text?[(postalText.text?.startIndex)!]
    let second = postalText.text?[(postalText.text?.index((postalText.text?.startIndex)!, offsetBy: 1))!]
    let third = postalText.text?[(postalText.text?.index((postalText.text?.startIndex)!, offsetBy: 2))!]
如果要检查
字符
是否为int,还可以将其设置为
字符串
,然后检查将
字符串
转换为
int
是否为非nil:

let firstCapitalized = String(first!).capitalized
这些情况都假设您的第一、第二和第三个都是非零的,并强制展开它们

编辑 我有一些空闲时间,并忽略了一些旧的帖子,所以我意识到我发布的这个答案并没有使用最好的编码形式。首先,强制展开任何东西都是一个坏主意(这会导致将来的崩溃),所以对于第一部分来说。这样做:

if Int("\(second!)") != nil {
    print("Is Integer")
}
let firstCapitalized = String(first ?? "").capitalized
如果
first==nil
,这至少会给您一个回退,然后您将被一个空字符串卡住

对于第二部分,我将使用可选的展开,而不是
if Int(“\(秒!)”)=无
。我想说更合适的方法是这样的:

if Int("\(second!)") != nil {
    print("Is Integer")
}
let firstCapitalized = String(first ?? "").capitalized

这将可选地展开字符
second
,如果它有一个值,则将其转换为整数(如果是一个,则通过可选的展开进行检查)。这是最安全的方法,可以防止您遇到任何运行时错误。

您应该发布原始字符串和所需的结果。您需要使用大写或大写字符串方法初始化字符串。
let first=String(postalText.text![postalText.text!.startIndex])。uppercased()
或者只提供一个范围而不是单个索引
让firstUppercased=postalText.text![postalText.text!.startIndex…postalText.text!.startIndex].uppercased()
@LeoDabus-我想我从来没有意识到这两者之间有区别