Wednesday 15 August 2012

java - Converting array-formatted string input to string array efficiently -



java - Converting array-formatted string input to string array efficiently -

say 1 has string input in form below:

{ 'oth', 'rej', 'rsto', 'rstos0', 'rstr', 's0', 's1', 's2', 's3', 'sf', 'sh' }

what efficient way convert array of strings each element beingness oth, rej, etc.?

i've done using string.replace() , string.split() , have considered utilize of regex-s same, wondering whether there more easier/intuitive way of doing so.

each of replace , split need iterate on entire string means need iterate on twice. scanner can in 1 go, need utilize delimiter representing non-word characters (non a-z a-z 0-9 _) can written in regex \\w.

so code can like

string text = "{ 'oth', 'rej', 'rsto', 'rstos0', 'rstr', 's0', 's1', 's2', 's3', 'sf', 'sh' }"; list<string> tokens = new arraylist<>(); scanner sc = new scanner(text); sc.usedelimiter("\\w+");// 1 or more non-word character while(sc.hasnext()) tokens.add(sc.next()); system.out.println(tokens);//[oth, rej, rsto, rstos0, rstr, s0, s1, s2, s3, sf, sh] sc.close();

java arrays string

No comments:

Post a Comment