Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Tokenize String with Commas and Line Delimiter

I'm making a simple String Tokenizer in Swift like I would in Java...but it's really not working out for me.

The end of each line in my data source delimited with "^" and the data is separated by comma's.

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

This is what I would do in Java...(I only want the first two strings in each line 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 could point me in the right direction that would really helpful.

I've 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 can't really find other resources on String Tokenizing in Swift. Thanks!

like image 798
stepheaw Avatar asked Feb 16 '15 00:02

stepheaw


1 Answers

This extends Syed's componentsSeperatedByString answer but with Swift's 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

like image 112
Price Ringo Avatar answered Sep 28 '22 06:09

Price Ringo