java - Splitting a string and extracting specific strings to array -
this question has answer here:
- how split string in java 28 answers
i having string "s".only substrings in single quotes must assigned string array.its may not necessary alternate words in single quotes.
string s = "username 'user1' username2 'user2' usermane3 'user3' 'user4'";
it must assigned below (only substrings single quotes)
string username[] ={'user','user1','user2','user4'};
what tried
string s1 = s.replace(system.getproperty("line.separator"), " "); //replacing newline single space string username[] = s1.split(" "); //separating string sub-string username[]={username,'user1',username2,'user2',username3, 'user3','user4'};
you split input using delimiter , take alternate strings.
string s = "username 'user1' username2 'user2 user21' usermane3 'user3'"; string[] tokens = s.split("'");//use delimiter ' value inside quote string[] usernames = new string[tokens.length / 2]; (int = 1, k = 0; < tokens.length; += 2) { system.out.println(tokens[i]); usernames[k++] = tokens[i]; }
if there no rule single username
have single user1
like
string s = "username 'user1' username2 'user2' usermane3 'user3' 'user4'";
you use logic strings in quotes below.
string s = "username 'user1' username2 'user2' usermane3 'user3' 'user4'"; arraylist<string> words = new arraylist(); string word = ""; boolean startquote = false; (int = 0; < s.length(); ++i) { char ch = s.charat(i); if (ch == '\'') { if (word.equals("")) startquote = true; else { words.add(word); word = ""; startquote = false; } } else if (startquote) { word += ch; } } system.out.println(words);
Comments
Post a Comment