tags:

views:

90

answers:

3

I have following problem:

Input String 1 : "A[SPACE]B[SPACE]C[SPACE][SPACE]D[SPACE][SPACE]E"
Input String 2 : "1-" OR "1,2" OR "3-"

If Input String 2 is 1- then I am supposed to return string from first word

If the input string is 3- then i am supposed to return string from 3rd word,
If the input string is 1,2 then I am supposed to return word 1 and 2

One cannot assume that more than one space is delimiter

For example

3- should return C[SPACE][SPACE]D[SPACE][SPACE]E

PLEASE CONSIDER [SPACE] as actual space character

+1  A: 

Use a regular expression which matches only a single space (i.e., something like "[^ ] [^ ]") to find the positions on which you should split your string into an array or some kind of list. Then return the relevant parts of your array.

Heinzi
+1  A: 

You didn't say what language so... Java! It's hacky, and assumes that the inputs are valid, but probably a good starting point

public void foo(String input, String q) {
  //First clean up the input string so that all tokens are delimited by one space
  input = input.replaceAll(" *", " ");

  String[] inputTokens = input.split(",");       
  String[] queries = q.split(",");
  for (String query : queries) {
    if (query.endsWith(-)) {
      query = query.replace("-", "");
      for (int i = Integer.parseInt(query), i <= inputTokens.length; i++) {
        System.out.println(inputTokens[i]);
      }
    } else {
      System.out.println(inputTokens[Integer.parseInt(query)]);
    }
  }
mlathe
I originally thought about something along these lines, but spotted that the OP wants multiple spaces preserved so you can't use `string.split` and `string.join` type functionality.
ChrisF
Actually the API is "String[] split(String regex)". So you could do a regex like " *", or something like that.
mlathe
A: 

Here's a way to do it in Python

import re

def f(s1,s2):
    items = re.findall("[^ ]+| +",s1)
    result = []
    for idx in s2.split(','):
        i,j,_ = idx.partition("-")
        i=int(i)-1
        result.append(''.join(items[i:None if j else i+1]))
    return ','.join(result)

assert f("A B C  D  E", "3-") == "C  D  E"
assert f("A B C  D  E", "1,2") == "A,B"
assert f("A B C  D  E", "4-,1,2") == "D  E,A,B"
gnibbler