-3

I have the following string:

string input = "  2  1";

It is 2 spaces followed by a 2 and then 2 more spaces followed by a 1. I want to do a replace on it, but I only want to replace the spaces between the 2 and the 1 with 0's and I do not want to use RegEx if possible?

The end result should look like this:

string result = "  2001";

20 340400 1 - 20-34-04-00-00001.0-0000.00

20 340400 500 - 20-34-04-00-00500.0-0000.00

20 340900 C - 20-34-09-00-0000C.0-0000.00

20 3435OG 1 1 - 20-34-35-OG-00001.0-0001.00

20 3435OG 2 10 - 20-34-35-OG-00002.0-0010.00

20 3435OG A - 20-34-35-OG-0000A.0-0000.00

20 3436AA 1 4A - 20-34-36-AA-00001.0-0004.A

20 3436AA 2 10B - 20-34-36-AA-00002.0-0010.B

20 353100 268 - 20-35-31-00-00268.0-0000.00

20G3402AI 1 401 - 20G-34-02-AI-00001.0-0004.01

20G3403AI 7 1 - 20G-34-03-AI-00007.0-0001.00

20G3416MK 1701 - 20G-34-16-MK-00000.0-0017.01

21 3410OM 148 - 21-34-10-OM-00000.0-0147.00

A few things I have noticed is that the first 4 parts are put together, most of the spaces and decimals are removed. I have had success without regex in most cases, but it fails for some.

4

7 回答 7

2

怎么样:

static string ReplaceSpacesWithZerosExceptLeading(string s)
{
    return s.TrimStart(' ').Replace(' ', '0').PadLeft(s.Length);
}

这将删除前导空格,然后用零替换其余空格,然后重新放置前导空格。

编辑:没关系,这个答案已经存在......

于 2012-11-09T19:34:35.327 回答
1
string input = "  2  1";
string result = string.Format("  {2}00{4}", input.Split(' ')); //Gives "  2001"
于 2012-11-09T19:40:51.087 回答
0

只是为了好玩,您可以使用 Linq:

string result = string.Format("{0}{1}{2}",
                   new string(input.Take(3).ToArray()), //get first three values
                   "00", //insert 00
                   new string(input.Skip(5).ToArray())); //get last value
于 2012-11-09T19:54:49.477 回答
0
var result = input.TrimStart().Replace(' ', '0'); // "2001"

如果前导空格很重要,那么:

var result = input.TrimStart().Replace(' ', '0').PadLeft(input.Length, ' '); 
于 2012-11-09T19:30:57.643 回答
0

尝试(Input.Trim()).Replace(" ", "0");

于 2012-11-09T19:30:59.497 回答
0

You really should use RegEx for this, but you could also try:

input.Replace(input.Trim(), input.Trim().Replace(" ", "0"));

Obviously it's not optimal, but it should do the trick.

于 2012-11-09T19:32:40.383 回答
0
string txt = "  2  1";
string txt1 = txt.Substring(0, (txt.Length - txt.TrimStart().Length)) + txt.TrimStart().Replace(" ", "0");
Debug.WriteLine(txt1);

或者如果数字在范围内

long num = long.Parse(txt.Replace(" ", "0"));
txt1 = num.ToString().PadLeft(txt.Length);
Debug.WriteLine(txt1);
于 2012-11-09T19:35:55.480 回答