如何遍历一个字符串数组并获取Swift中的子字符串?

时间:2016-12-13 08:14:31

标签: ios arrays swift swift3 substring

首先,我觉得我的要求不同,这就是我提出这个问题的原因,但必要时会标记重复。

现在,我现在有一个像这样的字符串数组:

January 27

我知道如何只提取每个索引的日期部分:

February 28

结果:March 29arrayvar1

我的问题是,如何循环浏览var2并仅提取当月的前3个字符,将其存储在for index in 0..<array.count { if let range = array[index].range(of: ",") { date = array[index][array[index].startIndex..<range.lowerBound] let nextArray = date.components(separatedBy: " ") let month = nextArray[0] let day = nextArray[1] } } 中,然后提取日期,将它存储在month = January中,一次又一次地以干净有效的方式存储?

我知道我可以做到这样的事情:

day = 27

结果:month<!DOCTYPE html> <html> <head> <script src="js/jquery-3.1.1.min.js" type="text/javascript"></script> <script src="2.js" type="text/javascript"></script> <script src="1.js" type="text/javascript"></script> </head> <body> <div id="content"> </div> </body> </html> 等。

然而,我觉得这只是凌乱,而且不干净。另外,我仍然需要从$(document).ready(function() { $('#content').html("<span>test3</span>"); // Works fine (i can see test3 on the page). showLogin(); }); 中提取前3个字符。

1 个答案:

答案 0 :(得分:0)

试试这个:

var months = [String]()
var days = [String]()
var array = ["January 27, 5:00PM - 10:00PM", "February 28, 11:00AM - 10:00PM", "March 29, 11:00AM - 9:00PM"]

array.forEach() {
    let monthAndDay = $0.components(separatedBy: ",")

    let dateFormatter = DateFormatter()

    dateFormatter.dateFormat = "MMM dd"
    let date = dateFormatter.date(from: monthAndDay.first!)

    let dateFormatterMonth = DateFormatter()
    dateFormatterMonth.dateFormat = "MMM"
    months.append(dateFormatterMonth.string(from: date!))

    let dateFormatterDay = DateFormatter()
    dateFormatterDay.dateFormat = "dd"
    days.append(dateFormatterDay.string(from: date!))
}

print(months) // Jan, Fer, Mar
print(days) // 27, 28, 29