我在Java中制作一个简单的字符串标记符就像我在Java中那样...但它对我来说真的不起作用。
我的数据源中每行的结尾用" ^"分隔。并且数据由逗号分隔。
例如:" string 1,string 2,string 3,^,string 1,string 2,string 3,^"
这就是我在Java中所做的...(我只希望每行数据中的前两个字符串)
String delimeter = "^";
StringTokenizer tokenizedString = new StringTokenizer(responseString,delimeter);
String [] stringArray = new String [tokenizedString.countTokens()];
StringTokenizer tokenizedAgain;
String str1;
String str2;
String token;
for(int i =0; i< stringArray.length; i ++)
{
token = tokenizedString.nextToken();
tokenizedAgain = new StringTokenizer(token, ",");
tokenizedAgain.nextToken();
str1 = tokenizedAgain.nextToken();
str2 = tokenizedAgain.nextToken();
}
如果有人能指出我正确的方向,那将非常有帮助。
我看过这个:Swift: Split a String into an array
并且:http://www.swift-studies.com/blog/2014/6/23/a-swift-tokenizer
但是我无法在Swift中找到关于String Tokenizing的其他资源。谢谢!
答案 0 :(得分:6)
这扩展了Syed的componentsSeperatedByString答案,但使用Swift的地图来创建请求的Nx2矩阵。
let tokenizedString = "string 1, string 2, string 3, ^, string a, string b, string c, ^"
let lines = tokenizedString.componentsSeparatedByString("^, ")
let tokens = lines.map {
(var line) -> [String] in
let token = line.componentsSeparatedByString(", ")
return [token[0], token[1]]
}
println(tokens)
答案 1 :(得分:0)
var delimiter = "^"
var tokenDelimiter = ","
var newstr = "string 1, string 2, string 3, ^, string 1, string 2, string 3,^"
var line = newstr.componentsSeparatedByString(delimiter) // splits into lines
let nl = line.count
var tokens = [[String]]() // declares a 2d string array
for i in 0 ..< nl {
let x = line[i].componentsSeparatedByString(tokenDelimiter) // splits into tokens
tokens.append(x)
}
println(tokens[0][0])