Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1001973
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T07:45:35+00:00 2026-05-16T07:45:35+00:00

I am attempting to build a string extension method to trim a string to

  • 0

I am attempting to build a string extension method to trim a string to a certain length but with not breaking a word. I wanted to check to see if there was anything built into the framework or a more clever method than mine. Here’s mine so far (not thoroughly tested):

public static string SmartTrim(this string s, int length)
        {
            StringBuilder result = new StringBuilder();

            if (length >= 0)
            {
                if (s.IndexOf(' ') > 0)
                {
                    string[] words = s.Split(' ');
                    int index = 0;

                    while (index < words.Length - 1 && result.Length + words[index + 1].Length <= length)
                    {
                        result.Append(words[index]);
                        result.Append(" ");
                        index++;
                    }

                    if (result.Length > 0)
                    {
                        result.Remove(result.Length - 1, 1);
                    }
                }
                else
                {
                    result.Append(s.Substring(0, length));
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException("length", "Value cannot be negative.");
            }

            return result.ToString();
        }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T07:45:35+00:00Added an answer on May 16, 2026 at 7:45 am

    I’d use string.LastIndexOf – at least if we only care about spaces. Then there’s no need to create any intermediate strings…

    As yet untested:

    public static string SmartTrim(this string text, int length)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException();
        }
        if (text.Length <= length)
        {
            return text;
        }
        int lastSpaceBeforeMax = text.LastIndexOf(' ', length);
        if (lastSpaceBeforeMax == -1)
        {
            // Perhaps define a strategy here? Could return empty string,
            // or the original
            throw new ArgumentException("Unable to trim word");
        }
        return text.Substring(0, lastSpaceBeforeMax);        
    }
    

    Test code:

    public class Test
    {
        static void Main()
        {
            Console.WriteLine("'{0}'", "foo bar baz".SmartTrim(20));
            Console.WriteLine("'{0}'", "foo bar baz".SmartTrim(3));
            Console.WriteLine("'{0}'", "foo bar baz".SmartTrim(4));
            Console.WriteLine("'{0}'", "foo bar baz".SmartTrim(5));
            Console.WriteLine("'{0}'", "foo bar baz".SmartTrim(7));
        }
    }
    

    Results:

    'foo bar baz'
    'foo'
    'foo'
    'foo'
    'foo bar'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm attempting to build a method call from strings that have been passed into
I am attempting to build a Java web project on NetBeans 6.8, but I
Presently I am attempting to build a tool that will open a Microsoft Word
I am attempting to build std::vectors and std::maps of std::shared_ptrs , but they seem
I'm attempting to build some XML elements based on an XSLT string parameter. The
Attempting to build a C# NPAPI plugin I have found a tutorial which describes
Attempting to build a C# project which has numerous references to assemblies in NuGet
I'm attempting to build a JSF/Hibernate application using Java 7 and Tomcat 7. I
I am attempting to build a backup script that moves a tar file from
I'm attempting to build an app using the Sencha Touch 2 builder tools. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.