如何获取字符串的最后4个字符? [英] How to get last 4 characters of a string?

查看:68
本文介绍了如何获取字符串的最后4个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要分隔字符串的最后 4 个字母.我怎样才能把它分开?字符串的长度在变化.

I need to seperate the last 4 letters of a string. How can I seperate it? The length of string is changing.

例如:

var a = "StackOverFlow"
var last4 = a.lastFour //That's what I want to do
print(last4) //prints Flow

推荐答案

一个解决方案是 substringFromIndex

let a = "StackOverFlow"
let last4 = a.substringFromIndex(a.endIndex.advancedBy(-4))

后缀字符

let last4 = String(a.characters.suffix(4))

代码是 Swift 2

code is Swift 2

Swift 3:

在 Swift 3 中,第一个解决方案的语法已更改为

In Swift 3 the syntax for the first solution has been changed to

let last4 = a.substring(from:a.index(a.endIndex, offsetBy: -4))


Swift 4+:

在 Swift 4 中它变得更加方便:

In Swift 4 it becomes more convenient:

let last4 = a.suffix(4)

结果的类型是一个新的类型Substring,它在很多情况下表现为一个String.但是,如果子字符串应该离开它在其中创建的范围,则必须创建一个新的 String 实例.

The type of the result is a new type Substring which behaves as a String in many cases. However if the substring is supposed to leave the scope where it's created in you have to create a new String instance.

let last4 = String(a.suffix(4))

这篇关于如何获取字符串的最后4个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆