Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#
Tip/Trick

How to Split Long Strings into Manageable Portions and Display them in a MessageBox

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
16 Jun 2014CPOL2 min read 10.8K   4   5
An easy method for slicing long strings into "bite-sized" portions for episodic (serial) display

Convert Overwhelming Information Overload to Information on Demand

Sometimes you need the contents of a long string, such as an exception message that you want to display in a MessageBox like so:

C#
catch (Exception x)
{
    MessageBox.Show(string.Format("Boo-boo in buttonNoseBest_Click(): {0}", x));
}

But especially if the app throwing the exception is running on a puny device, such as a handheld, you may end up with more information than can fit into the limited real estate of the device's screen. To solve this problem, you can break the long string into whatever size you want, and then display each portion, one MessageBox.Show at a time. This code works for that:

C#
const int MAX_CHARS_TO_SHOW = 314;
            string msg = "YOU don't know about me without you have read a book by the name of The Adventures of Tom Sawyer; but that ain't no matter. " +
                "That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. "+
                "That is nothing. I never seen anybody but lied one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly -- "+
                "Tom's Aunt Polly, she is -- and Mary, and the Widow Douglas is all told about in that book, which is mostly a true book, with some stretchers, "+
                "as I said before. Now the way that the book winds up is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. "+
                "We got six thousand dollars apiece -- all gold. It was an awful sight of money when it was piled up. Well, Judge Thatcher he took it and put it "+
                "out at interest, and it fetched us a dollar a day apiece all the year round -- more than a body could tell what to do with. The Widow Douglas "+
                "she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular "+
                "and decent the widow was in all her ways; and so when I couldn't stand it no longer I lit out. I got into my old rags and my sugar-hogshead "+
                "again, and was free and satisfied. But Tom Sawyer he hunted me up and said he was going to start a band of robbers, and I might join if I would "+
                "go back to the widow and be respectable. So I went back. The widow she cried over me, and called me a poor lost lamb, and she called me a lot of "+
                "other names, too, but she never meant no harm by it. She put me in them new clothes again, and I couldn't do nothing but sweat and sweat, and "+
                "feel all cramped up. Well, then, the old thing commenced again. The widow rung a bell for supper, and you had to come to time. When you got to "+
                "the table you couldn't go right to eating, but you had to wait for the widow to tuck down her head and grumble a little over the victuals, "+
                "though there warn't really anything the matter with them, -- that is, nothing only everything was cooked by itself. In a barrel of odds and "+
                "ends it is different; things get mixed up, and the juice kind of swaps around, and the things go better.";

            int msglen = msg.Length;
            int charsDisplayed = 0;
            while (charsDisplayed < msglen)
            {
                int CharsToGrab = MAX_CHARS_TO_SHOW;
                int CharsLeft = msglen - charsDisplayed;
                if (CharsLeft < MAX_CHARS_TO_SHOW) CharsToGrab = CharsLeft;
                string msgepisode = msg.Substring(charsDisplayed, CharsToGrab);
                int episodeLen = msgepisode.Length;
                MessageBox.Show(msgepisode);
                charsDisplayed = charsDisplayed + episodeLen;
            }

This will give you the long string a piece at a time, like so:

Image 1

Tweak It

You may want less or more information at a time. Just change the value of MAX_CHARS_TO_SHOW accordingly. You probably also want to work with some string other than the first part of the first chapter of the first novel (in rank of importance, not chronology), at least first American novel.

Improve It

You may have noticed that the splits are not done on sentences, or even words, but on characters, and so sometimes (usually) the start of a word will appear at the end of one MessageBox.Show(), and its ending will appear at the beginning of the next one. This works for quick- and-dirty debugging type stuff, but for something "golden," you will want to at least break the long string into words first or, better yet, sentences. Halve at it!

Apologies / Kudos / Credit to a PropellorHead

A cat calling himself PIEDBALDconsult came up with a more elegant way to do this (using RegEx). You can see it here.

I had a hard time understanding his code at first, but once I saw through the formatting and naming, I finally got it to compile, and it works great - the words are no longer chopped in the middle. Here is my version of his version of my version:

C#
private void buttonItUp_Click(object sender, EventArgs e)
{
    int MAX_CHARS_TO_SHOW = 314;
    string msg = "YOU don't know about me without you have read a book by the name of The Adventures of Tom Sawyer; but that ain't no matter. " +
        "That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. " +
        "That is nothing. I never seen anybody but lied one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly -- " +
        "Tom's Aunt Polly, she is -- and Mary, and the Widow Douglas is all told about in that book, which is mostly a true book, with some stretchers, " +
        "as I said before. Now the way that the book winds up is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. " +
        "We got six thousand dollars apiece -- all gold. It was an awful sight of money when it was piled up. Well, Judge Thatcher he took it and put it " +
        "out at interest, and it fetched us a dollar a day apiece all the year round -- more than a body could tell what to do with. The Widow Douglas " +
        "she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular " +
        "and decent the widow was in all her ways; and so when I couldn't stand it no longer I lit out. I got into my old rags and my sugar-hogshead " +
        "again, and was free and satisfied. But Tom Sawyer he hunted me up and said he was going to start a band of robbers, and I might join if I would " +
        "go back to the widow and be respectable. So I went back. The widow she cried over me, and called me a poor lost lamb, and she called me a lot of " +
        "other names, too, but she never meant no harm by it. She put me in them new clothes again, and I couldn't do nothing but sweat and sweat, and " +
        "feel all cramped up. Well, then, the old thing commenced again. The widow rung a bell for supper, and you had to come to time. When you got to " +
        "the table you couldn't go right to eating, but you had to wait for the widow to tuck down her head and grumble a little over the victuals, " +
        "though there warn't really anything the matter with them, -- that is, nothing only everything was cooked by itself. In a barrel of odds and " +
        "ends it is different; things get mixed up, and the juice kind of swaps around, and the things go better.";
        
    foreach (string s in BreakItUpWithRegex(msg, MAX_CHARS_TO_SHOW))
    {
        MessageBox.Show(s);
    }
}

private static System.Collections.Generic.IEnumerable<string> BreakItUpWithRegex(string text, int maxlen)
{
    string regex = System.String.Format(@"(?s).{{1,{0}}}(?=(\b|$))", maxlen);
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
    System.Text.RegularExpressions.MatchCollection m = reg.Matches(text);
    
    for (int i = 0; i < m.Count; i++)
    {
        yield return (m[i].Value);
    }
    
    yield break;
}</string>

And voila! Now the verbiage is more sensibly split:

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
General[My vote of 2] Please improve it Pin
Daniele Rota Nodari16-Jun-14 21:05
Daniele Rota Nodari16-Jun-14 21:05 
GeneralRe: [My vote of 2] Please improve it Pin
B. Clay Shannon17-Jun-14 3:28
professionalB. Clay Shannon17-Jun-14 3:28 
GeneralRe: [My vote of 2] Please improve it Pin
Daniele Rota Nodari17-Jun-14 5:24
Daniele Rota Nodari17-Jun-14 5:24 
GeneralIt's been done before... Pin
Matt T Heffron16-Jun-14 10:53
professionalMatt T Heffron16-Jun-14 10:53 
GeneralRe: It's been done before... Pin
B. Clay Shannon16-Jun-14 11:06
professionalB. Clay Shannon16-Jun-14 11:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.