5

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!

Community
  • 1
  • 1
stepheaw
  • 1,683
  • 3
  • 22
  • 35

2 Answers2

6

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

Price Ringo
  • 3,424
  • 1
  • 19
  • 33
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])
Syed Tariq
  • 2,878
  • 3
  • 27
  • 37
  • Hey thanks for the response! I tried out your code the logic behind it is very insightful...I would have never thought to make a 2D array...but when I get the values from the 2D array..."println(tokens[1][0])" is Line 1..string 0.. but points to the first"^" delimiter...and the array thinks this is the first entry in the new line...and it also prints blank in the console. Ideally I would like "println(tokens[1][0])" to print "string 1" (of line 2) but it is blank in the console. But anyways...Thanks again. Much Appreciated!!! – stepheaw Feb 16 '15 at 06:02