How to tokenize a comma-delimited string line

I am making a simple string tokenizer in Swift, as in Java, but it really does not work for me.

The end of each line in my data source is limited to "^" and the data is separated by a comma.

For example: "line 1, line 2, line 3, ^, line 1, line 2, line 3, ^"

This is what I will do in Java ... (I only need the first two rows in each row of data)

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(); } 

If someone can point me in the right direction, that would be really helpful.

I looked at this: Swift: split a string into an array

and this: http://www.swift-studies.com/blog/2014/6/23/a-swift-tokenizer

but I cannot find other resources for String Tokenizing in Swift. Thanks!

+5
source share
2 answers

This extends SyedsSeperatedByString's answer, but using a Swift map to create the requested Nx2 matrix.

 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) 

enter image description here

+5
source
 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]) 
0
source

Source: https://habr.com/ru/post/1213432/


All Articles