Panelen



Forumnavigering
Senast inloggade
RSS
Sponsorer
Tips > ASP.NET 1.x och 2.x

korta ner en sträng efter hela ord

Tänkte fortsätta med tipset som pbf delade med sig.
Då det kan bli missförstånd om man delar ord på fel plats så använder jag mig av att dela hela ord.

C#:

/// <summary>
/// Try to shorten the Sentence if its longer then the numberOfWords it will add three
/// periods to inform the visitor that the text contains more then numberOfWords
/// </summary>
/// <param name="stringValue">The string value to shorten</param>
/// <param name="numberOfWords">how many words the function will return</param>
/// <returns>Returns a shorter version (if possible) of the stringValue</returns>
public static string shortString(string stringValue, int numberOfWords)
{
    char[] delimiterChars = { ' ', '\t'};
    string[] words = stringValue.Split(delimiterChars);
    if (words.Length - 1 > numberOfWords)
    {
        return string.Join(" ", words, 0, numberOfWords) + "...";
    }
    return stringValue;
}
/// <summary>
/// Try to return a shorter version of a text
/// </summary>
/// <param name="stringValue">The string value to shorten</param>
/// <returns>Returns a shorter version (if possible) of the stringValue</returns>
public static string shortString(string stringValue)
{
    return shortString(stringValue,6);
}


VB.NET:
''' <summary>
''' Try to return a shorter version of a text
''' </summary>
''' <param name="stringValue">The string value to shorten</param>
''' <param name="numberOfWords">how many words the function will return</param>
''' <returns>Returns a shorter version (if possible) of the stringValue</returns>
''' <remarks></remarks>
Public Shared Function shortString(ByVal stringValue As String, Optional ByVal numberOfWords As Integer = 6) As String
    Dim delimiterChars As Char() = {" "c, Chr(9)}
    Dim words As String() = stringValue.Split(delimiterChars)
    If words.Length - 1 > numberOfWords Then
        Return String.Join(" ", words, 0, numberOfWords) + "..."
    End If
    Return stringValue
End Function


test c#:
string test = shortString("Im testing to see if this can split my words correctly", 3); //Will split after 3 words

string test = shortString("Im testing to see if this can split my words correctly"); //Will split on 6 words


Test VB.NEt:
Dim Test as string = shortString("Im testing to see if this can split my words correctly", 3) 'Will split after 3 words

Dim Test as string = shortString("Im testing to see if this can split my words correctly") 'Will split on 6 words

Detta tips skapades 2008-07-20 13:45:12 av voigtan. Det har lästs 589 gånger. ||

Kommentarer

pbf sa den 20 juli 2008 kl 14:28:
En ytterst eminent fortsättning.
© Copyright 2007-2009 Shadi Domat | Version 3.0 | Sidkarta | Policy