Humanizr / Humanizer

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities
Other
8.69k stars 964 forks source link

Correct String spacing #1076

Open varyamereon opened 3 years ago

varyamereon commented 3 years ago

Feature request

Would love it if there was a way of removing extra spacing in strings, for example (with * representing space):

Bob**Smith => Bob Smith (Two spaces between bob and smith in original) *Dave Jones => Dave Jones (OK this could be done with Trim() 🤷‍♂️)

My use case is I am parsing a large CSV file, and at the moment I am converting capitalized names into title case names, but have noticed some records contain extra spacing (a mistake from original user entry). I can remove these manually but it would be great if there was a feature to do this whilst I convert the casing.

Yomodo commented 3 years ago

Naive implementation: "Bob**Smith".Replace("**", "*");

Your question has nothing to do with MudBlazor.

varyamereon commented 3 years ago

Naive implementation: "BobSmith".Replace("", "*");

Works if the original string contains two spaces in a row. If it contained three it wouldn't work etc. Certainly possible to write an extension method myself but thought it sounded like a nice thing for this library.

Your question has nothing to do with MudBlazor.

Indeed, it's regarding Humanizer ;)

Yomodo commented 3 years ago

I'm so sorry! I just re-enabled notifications for Humanizer and assumed it was MudBlazor. Apologies!

varyamereon commented 3 years ago

No worries 😜

Gakk commented 3 years ago

@varyamereon: The project must respond if they want this feature built in or not, but you can use Humanizer to accomplish this by using a custom StringTransformer. Since the static class To can not be extended, we have solved this by creating a similar With class:

    public static class With
    {
        /// <summary>
        /// Replaces multiple following spaces with a single space.
        /// </summary>
        public static ICulturedStringTransformer SingleSpaceOnly => new SingleSpaceOnlyTransformer();

        private class SingleSpaceOnlyTransformer : ICulturedStringTransformer
        {
            public string Transform(string input)
            {
                return Transform(input, null);
            }

            public string Transform(string input, CultureInfo culture)
            {
                if (string.IsNullOrEmpty(input))
                    return input;

                const string doubleSpace = "  ";
                while (input.Contains(doubleSpace))
                    input = input.Replace(doubleSpace, " ");

                return input;
            }
        }
    }

You can then use this as normal transform, also in combination with other string transformers:

"this is   my text".Transform(To.SentenceCase, With.SingleSpaceOnly)
varyamereon commented 3 years ago

@Gakk thanks for the tip!