1

I am having a String "S".Only Substrings in single quotes must be assigned to a String Array.Its may not be necessary alternate words are in single quotes.

String S = "Username 'user1'
             Username2 'user2'
             Usermane3 'user3' 'user4'";

It must be assigned as below (only Substrings with single Quotes)

 String Username[] ={'user','user1','user2','user4'};

What I tried

 String s1 = S.replace(System.getProperty("line.separator"), " ");
   //replacing newline with single space
 String Username[] = s1.split(" ");
  //separating string into sub-string
 Username[]={Username,'user1',Username2,'user2',Username3, 'user3','user4'};
Ravichandra
  • 2,162
  • 4
  • 24
  • 36
  • 1
    Many answers on the way ..BTW, what you have tried so far ? – Suresh Atta Aug 31 '15 at 06:49
  • A simple google query "how to split a string in java" gave me the link to the SO post [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – LBes Aug 31 '15 at 06:55
  • @LBesacon I am looking for solution to extract substrings in single quotes not to looking how to split. – Ravichandra Aug 31 '15 at 07:15

2 Answers2

7

You could split the input using a delimiter and take the alternate strings.

String S = "Username 'user1' Username2 'user2 user21' Usermane3 'user3'";
String[] tokens = S.split("'");//use delimiter as ' to get the value inside the quote
String[] usernames = new String[tokens.length / 2];
for (int i = 1, k = 0; i < tokens.length; i += 2) {
    System.out.println(tokens[i]);
    usernames[k++] = tokens[i];
}

If there is no rule that a Single Username would have a single user1 like

String S = "Username 'user1' Username2 'user2' Usermane3 'user3' 'user4'";

You could use a logic to get only the strings in the quotes as below.

String S = "Username 'user1' Username2 'user2' Usermane3 'user3' 'user4'";
ArrayList<String> words = new ArrayList();
String word = "";
boolean startQuote = false;
for (int i = 0; i < 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);
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
0

This will pretty print the array as described in @Uma Kanth's version. If you need it to.

System.out.print("usernames = [");
for (int i = 0; i < usernames.length; i++) {
    String username = usernames[i];
    System.out.print(username);
    if (i < usernames.length - 1) {
        System.out.print(", ");
    }
}
System.out.println("]");
Craig
  • 2,286
  • 3
  • 24
  • 37