Home > database >  How to add string padding in textbox by importing textfile that has 2 values
How to add string padding in textbox by importing textfile that has 2 values

Time:08-17

This is my code for importing txt file to TextBox (it works). Now my question is how to add string padding like this:

dean [email protected]

Now it shows just: dean harris, [email protected].

I looked up a lot but didn't get any good result. I tried using the documentation but I couldn't figure it out. ==> https://docs.microsoft.com/en-us/dotnet/standard/base-types/padding

Thanks in advance!

private void BtnInlezen_Click(object sender, RoutedEventArgs e)
{
    string[] lines = File.ReadAllLines(txtFile);
    try
    {
        using (StreamReader file = new StreamReader(txtFile))
        {
            StringBuilder builder = new StringBuilder();

            while (!file.EndOfStream)
            {
                builder.Append(file.ReadLine().Replace("\"", ""));
                builder.AppendLine();
            }
            
            TxtResultaat.Text = builder.ToString();
        }
    }
    catch (Exception ex)
    {
        if (!File.Exists(txtFile))
        {
            MessageBox.Show(ex.Message, "File not found");
        }
        else
        {
            MessageBox.Show("an unknown error has occurred");
        }
        return;
    }
}

CodePudding user response:

I'm not sure how you want to pad the string so here are two ways. The first center pads the string so they all have the same length and the second aligns the email addresses.

public static string CenterPad(string s, int maxLength, string delimeter, char replaceWith='.')
{
    int numDots = maxLength - s.Length   delimeter.Length;
    return s.Replace(delimeter, new string(replaceWith, numDots));
}
public static string AlignSecond(string s, int maxLength, string delimeter, char replaceWith='.')
{
    string [] parts = s.Split(new string[]{delimeter}, StringSplitOptions.None);
    return parts[0].PadRight(maxLength, replaceWith)   parts[1];
}
public static void Main()
{
    string [] tests = {"dean harris, [email protected]",
                       "john smith, [email protected]",
                       "sally washington, [email protected]"};
    foreach (var s in tests) {
        Console.WriteLine(CenterPad(s, 50, ", "));
    }
    Console.WriteLine();
    foreach (var s in tests) {
        Console.WriteLine(AlignSecond(s, 25, ", "));
    }
}

Output:

dean [email protected]
john [email protected]
sally [email protected]

dean [email protected]
john [email protected]
sally [email protected]

CodePudding user response:

If you want to add a string pad, you can use these methods https://docs.microsoft.com/en-us/dotnet/standard/base-types/padding of class String , and manipulate the string before assing value to the property of object TxtResultaat.

  • Related