删除字符串中数字之间的空格

时间:2015-02-25 14:15:40

标签: algorithm replace spaces digits

原文:“我有M5 2 0 0,我喜欢它”
意图:“我有M5200,我喜欢它”

你如何实现这个算法或给出一个代码示例? 我相信这个问题在许多编程语言中都是有效的,所以我不会问它是否具体。

4 个答案:

答案 0 :(得分:3)

C#示例(替换为正则表达式):

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(" ", "");
}));

答案 1 :(得分:2)

对于没有正则表达式的语言:遍历文本。如果当前字母是空格而周围的字母是数字,则不要将其添加到结果中。

示例Python实现:

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)

结果:

I have the M5200 and I like it

答案 2 :(得分:2)

对于python,您可以使用:

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)

其中\ 1代表第一组\ d +而第二组不会被替换?= \ d因为仅用于匹配。

结果:我有M5200,我喜欢它

答案 3 :(得分:1)

Java解决方案:

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);
}
相关问题