Thursday, 26 November 2020

C# - Truncate characters from string by keeping right side string with the specific length

 

Challenge

Consider a scenario where you are uploading a file in a website and prcoess the file by appending the date at the end of the file name and saves in a location and then saving the uploaded file name in the database. Post uploading the file you are displaying all the submitted files in a grid like below.

Uploaded filename: Developer_Profile.xlsx
Saved filename appended with date: Developer_Profile_11242020.xlsx
https://dotnetcookie.blogspot.com/
Consider the column length for the filename is 150. If the uploaded file name length is more than 150 and there is no length validation before inserting into database then database will throw the exception. So we need to add a validation before uploading. Assume that the client doesn't want to restrict the upload if the file name length is more than 150 characters. Instead client comes with the below requirement.

- If the file length is greater than 150
- Truncate filename to 150 characters, but keep the right side portion which is date part along with extension.

Example: Uploaded file with file name length more than 150
Filename: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page editors now use Lorestandard_11242020.xlsx

Keep the date part and remove/trim the additional characters highlighted above.

Truncated filename with 150: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page edit_11242020.xlsx

Below is the extesion method which will truncate the file name and the respective unit testcacses. Follow the code comments which is self explanatory.

Extension method to truncate string

        /// <summary>
        /// If input length is greater than the truncate length value
        /// Trims the input with length truncate length value.
        /// Keeps the right side of the input value
        /// </summary>
        /// <param name="value">Input value</param>
        /// <param name="truncateLength">Truncates input if the input length is greater than this</param>
        /// <param name="rightLengthToKeep">The right side string length which needs to take while truncating</param>
        /// <returns></returns>
        public static string TruncateRight(this string value, int truncateLength, int rightLengthToKeep)
        {
            var errorMessage = "Negative values are not allowed";

            // Handle empty, null and white spaces 
            if (string.IsNullOrWhiteSpace(value))
            {
                return value;
            }

            // Handle negative values
            if (truncateLength < 0)
            {
                throw new ArgumentOutOfRangeException("truncateLength", truncateLength, errorMessage);
            }

            // Handle negative values
            if (rightLengthToKeep < 0)
            {
                throw new ArgumentOutOfRangeException("rightLengthToKeep", rightLengthToKeep, errorMessage);
            }

            if (rightLengthToKeep > truncateLength)
            {
                errorMessage = $"rightLengthToKeep value ({rightLengthToKeep}) shoud be less than or equal to truncateLength ({truncateLength})";
                throw new ArgumentOutOfRangeException(errorMessage);
            }

            if (value.Length <= truncateLength)
            {
                return value;
            }

            // To skip middle range we need to take the left side end rage and right side start rage.
            int leftStringEndIndex = truncateLength - rightLengthToKeep;
            int rightStringStartIndex = value.Length - rightLengthToKeep;

            var finalResult = "";

            // Get left side value
            for (int i = 0; i < leftStringEndIndex; i++)
            {
                finalResult = finalResult + value[i];
            }

            // Get right side value
            for (int i = rightStringStartIndex; i < value.Length; i++)
            {
                finalResult = finalResult + value[i];
            }

            return finalResult;
        }

Unit tests

        [Fact]
        public void SkipRightThenTrimTest()
        {
            // Test filename: FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv
            // Total string length is 63

            // Null check
            string testString = null;
            Assert.Equal(null, testString.TruncateRight(40, 22));

            // Empty check
            testString = ""; 
            Assert.Equal("", testString.TruncateRight(40, 22));

            // Whitespace check
            testString = "  ";
            Assert.Equal("  ", testString.TruncateRight(40, 22));

            // Negative value check 
            testString = "FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv";
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(-22, 40));
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, -40));
            
            // Invalid range check
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, 40));

            // Truncate filename if it more than 22 chars and take right 22 characters
            Assert.Equal("_11242020_ErroFile.csv", testString.TruncateRight(22, 22)); 
           
            // Truncate filename if it is more than 40 chars and keep right 22 characters and left 18 chars
            Assert.Equal("FileNameToTestWith_11242020_ErroFile.csv", testString.TruncateRight(40, 22));
            
            // Take filename directly if the fielname lenth and truncate value length is equal
            Assert.Equal(testString, testString.TruncateRight(63, 22));
            
            // Take filename directly if the truncate value length is greater than the filename length
            Assert.Equal(testString, testString.TruncateRight(70, 22));
        }
    }

No comments: