senzacionale
senzacionale

Reputation: 20916

substring for words

text:

Sed ut perspiciatis unde omnis iste natus error sit voluptatem ac

i want to substring words not in regular way like word.Substring(1, 29).

regular way:

"Sed ut perspiciatis unde om"

but i want:

"Sed ut perspiciatis unde"

so only full words are shown. if word is cut inside one word before will be shown. hope understand what i am looking for.

Upvotes: 6

Views: 4804

Answers (2)

John Arlen
John Arlen

Reputation: 6689

public static String ParseButDontClip(String original, int maxLength)
{
    String response = original;

    if (original.Length > maxLength)
    {
        int lastSpace = original.LastIndexOf(' ', original.Length - 1, maxLength);
        if (lastSpace > -1)
            response = original.Substring(0, lastSpace);
    }
    return response;
}

String.LastIndexOf second's parameter is actually the END of the substring to search for - and longest is how far back towards the start you need to go.

Gets me every time I use it.

Upvotes: 12

JAiro
JAiro

Reputation: 5999

You could split it by white spaces and then play with the array

Upvotes: 1

Related Questions