-4

original: "I have the M5 2 0 0 and I like it"
intended: "I have the M5200 and I like it"

How would you achieve this as an algoritm or give a code example? I believe this question is valid in many programming languages so I won't ask it for a specific one.

Adrian Cumpanasu
  • 1,028
  • 1
  • 10
  • 24

4 Answers4

3

C# sample (replacing with regular expression):

String original = "I have the M5 2 0 0 and I like it";

String result = Regex.Replace(original, @"\d( *\d*)*\d", 
  (MatchEvaluator) (match => {
    return match.Value.Replace(" ", "");
}));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

For languages that don't have regular expressions: iterate through the text. If the current letter is a space and the letters surrounding it are digits, then don't add it to the result.

Sample Python implementation:

text = "I have the M5 2 0 0 and I like it"
result = []
for i in range(len(text)):
    if i > 0 and i < len(text)-1:
        prev = text[i-1]
        next = text[i+1]
        if text[i] == ' ' and prev.isdigit() and next.isdigit():
            continue
    result.append(text[i])
print "".join(result)

Result:

I have the M5200 and I like it
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 1
    text[i] == ' ' will not consider tab spaces – profimedica Feb 25 '15 at 14:53
  • 2
    I didn't know whether the OP meant "the literal space character" or "any whitespace" when he said space. No problem, though - just replace `text[i] == ' '` with `text[i].isspace()` if you want to detect tabs as well. – Kevin Feb 25 '15 at 14:57
  • I guess I should also point out that this won't remove _multiple_ spaces between digits. ex. the output for `a 1(space)(space)(space)2 b' will be the same as its input. It's not totally clear to me what behavior the OP would like in that case. – Kevin Feb 25 '15 at 14:59
2

For python you can use:

import re
line = 'I have the M5 2 0 0 and I like it'
line = re.sub(r'(\d+)\s+(?=\d)',r'\1', line)
print(line)

where \1 stands for the first group \d+ and the second group will not be replaced ?=\d because is only used for matching.

Result: I have the M5200 and I like it

profimedica
  • 2,716
  • 31
  • 41
1

A Java solution:

public static void main(String[] args) {
    String input = "I have the M5 231 0 0 and I like it";
    String output = "";
    if ( input.length() > 0 ) {
        output += input.charAt(0);
    }
    for ( int i = 1 ; i < input.length()-1 ; i++ ) {
        if ( Character.isDigit(input.charAt(i-1)) &&
             Character.isDigit(input.charAt(i+1)) &&
             Character.isSpaceChar(input.charAt(i)) ) {
            continue;
        } else {
            output += input.charAt(i);
        }
    }
    if ( input.length() > 1 ) {
        output += input.charAt(input.length() - 1);
    }
    System.out.println(output);
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199