简体   繁体   中英

string.PadRight() doesn't seem to work in my code

I have a Powershell output to re-format, because formatting gets lost in my StandardOutput.ReadToEnd().
There are several blanks to be removed in a line and I want to get the output formatted readable. Current output in my messageBox looks like

Microsoft.MicrosoftJigsaw     All
Microsoft.MicrosoftMahjong     All

What I want is

Microsoft.MicrosoftJigsaw     All
Microsoft.MicrosoftMahjong    All

What am I doing wrong?
My C# knowledge still is basic level only

I found this question here, but maybe I don't understand the answer correctly. The solution doesn't work for me.
Padding a string using PadRight method

This is my current code:

string first = "";
string last = "";
int idx = line.LastIndexOf(" ");
if (idx != -1)
    {
     first = line.Substring(0, idx).Replace(" ","").PadRight(10, '~');
     last = line.Substring(idx + 1);
    }
MessageBox.Show(first + last);

The PadRight(10 is not enough, it is the size of the complete string.

I would probably go for something like:

string[] lines = new[] 
{
    "Microsoft.MicrosoftJigsaw     All",
    "Microsoft.MicrosoftMahjong            All"
};

// iterate all (example) lines
foreach (var line in lines)
{
    // split the string on spaces and remove empty ones 
    // (so multiple spaces are ignored)
    // ofcourse, you must check if the splitted array has atleast 2 elements.
    string[] splitted = line.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    // reformat the string, with padding the first string to a total of 40 chars.
    var formatted = splitted[0].PadRight(40, ' ') + splitted[1];

    // write to anything as output.
    Trace.WriteLine(formatted);
}

Will show:

Microsoft.MicrosoftJigsaw               All
Microsoft.MicrosoftMahjong              All

So you need to determine the maximum length of the first string.

String.PadLeft() first parameter defines the length of the padded string, not padding symbol count.

Firstly, you can iterate through all you string, split and save.

Secondly, you should get the longest string length.

Finally, you can format strings to needed format.

var strings = new [] 
{
    "Microsoft.MicrosoftJigsaw     All",
    "Microsoft.MicrosoftMahjong     All"
};

var keyValuePairs = new List<KeyValuePair<string, string>>();

foreach(var item in strings)
{
    var parts = item.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries);

    keyValuePairs.Add(new KeyValuePair<string, string>(parts[0], parts[1]));
}

var longestStringCharCount = keyValuePairs.Select(kv => kv.Key).Max(k => k.Length);
var minSpaceCount = 5; // min space count between parts of the string

var formattedStrings = keyValuePairs.Select(kv => string.Concat(kv.Key.PadRight(longestStringCharCount + minSpaceCount, ' '), kv.Value));  

foreach(var item in formattedStrings)
{
    Console.WriteLine(item);
}

Result:

Microsoft.MicrosoftJigsaw      All
Microsoft.MicrosoftMahjong     All

Assuming the length of second part of your string is 10 but you can change it. Try below piece of code:

Function:

private string PrepareStringAfterPadding(string line, int totalLength)
{
    int secondPartLength = 10;
    int lastIndexOfSpace = line.LastIndexOf(" ");
    string firstPart = line.Substring(0, lastIndexOfSpace + 1).Trim().PadRight(totalLength - secondPartLength);
    string secondPart = line.Substring(lastIndexOfSpace + 1).Trim().PadLeft(secondPartLength);
    return firstPart + secondPart;
}

Calling:

    string line1String = PrepareStringAfterPadding("Microsoft.MicrosoftJigsaw     All", 40);
    string line2String = PrepareStringAfterPadding("Microsoft.MicrosoftMahjong     All", 40);

Result:

Microsoft.MicrosoftJigsaw            All
Microsoft.MicrosoftMahjong           All

Note:

Code is given for demo purpose please customize the totalLength and secondPartLength and calling of the function as per your requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM