2

如何删除长文本中字符附近的一个或多个空格。我不想删除匹配字符串附近不存在的其他空格。我只想删除匹配字符旁边的所有空格,而不是输入字符串的所有空格。例如:

[text][space][space]![space][text]                should result in [text]![text]
[text][space][space]![space][space][space][text]  should result in [text]![text]
[text][space]![space][space][text]                should result in [text]![text]
[text][space]![space][text]                       should result in [text]![text]
[text]![space][space][text]                       should result in [text]![text]
[text][space][space]![text]                       should result in [text]![text]
[text][space][space]!                             should result in [text]!
![space][space][text]                             should result in ![text]

我要写的代码是:

for (int i = 0 to length of string)
{
 if (string[i] == character)  //which is the desired character "!"
 {
  int location = i+1;
  //remove all whitespace after the character till a non-whitespace character
  //is found or string ends
  while (string[location] == whitespace)
  {
   string[location].replace(" ", "");
   location++;
  }

  int location = i-1;
  //remove all whitespace before the character till a non-whitespace character
  //is found or string ends
  while (string[location] == whitespace)
  {
   string[location].replace(" ", "");
   location--;
  }
 }
}

有没有更好的方法来使用正则表达式删除字符附近的空格?

更新:我不想删除与匹配字符串相邻的其他空格。例如:

some_text[space]some_other_text[space][space]![space]some_text[space]some_other_text 
is
 some_text[space]some_other_text!some_text[space]some_other_text
4

1 回答 1

5
Regex rgx = new Regex(pattern);
string input = "This is   text with   far  too   much   " + 
                 "whitespace.";
string pattern = "\\s*!\\s*";
string replacement = "!";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

taken from http://msdn.microsoft.com/de-de/library/vstudio/xwewhkd1.aspx

于 2013-08-21T08:33:23.553 回答