Using delimiter to organize a set

Is there a way to use a delimiter every other time the delimiter symbol comes up?

For example, you have a set of Strings separated by commas like so: (yes, 2, my, 15, face, 9) I want the word to be paired with the number immediately following it, and to separate the above set into the following: ((yes, 2), (my, 15), (face, 9)). I am using a custom List for this, so in realty I add each element [ex. (yes, 2]) to the list.

Answers


You can use regex pattern. This code describes a solution (since I don't know how you want to store it, I am just printing it out).

String data = "yes,2,my,15,face,9";

Pattern p = Pattern.compile("[^,]*,[^,]*,?");
Matcher matcher = p.matcher(data);

while (matcher.find()) {
    String[] splitted = matcher.group().split(",");
    System.out.println(splitted[0]);
    System.out.println(splitted[1]);
    System.out.println("******************");
}

This outputs :

yes
2
******************
my
15
******************
face
9
******************

Another solution would be to use Scanner with delimiter "," and pair returned parts.


You might simply parse the string using the delimiter (comma in your case), and then process each pair int an entry, and make a list of those entries. (Looks like homework, so exact code not specified).


Why do you care about 'delimiter'? If I were you, I will do something like this.

String input = "Yes, 2, my, 15, face, 9";
String delimiter = ",";
List<Pair> s = createPairs(Arrays.asList(input.split(delimiter))); 

List<Pair> createPairs(List<String> input) {
  // read 2 at a time and create a Pair Object 
}  

`

This way, I can have any delimiter and keep my API clean. If this is just one time job and the pattern fixed(string followed by ,(comma) and by number) then you can use regular expression too to match this. Just google it you will find tons of.


Need Your Help

Unmanaged Resources, IDisposable and Custom Types

c# garbage-collection idisposable unmanagedresources idbconnection

yet another topic on the subject as I got tired of reading countless topics to find an answer to my questions :)

how to add visual c++ template to visual studio 2010 ultimate

visual-studio-2010 visual-c++

i recently installed visual studio 2010 ultimate with visual c#. Now i want to program in visual c++, how can i install the visual c++ template?