Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Soeren Sprogoe 575 posts 259 karma points
    Aug 18, 2009 @ 14:00
    Soeren Sprogoe
    0

    Inserting a char at every X pos. in a string

    Been trying to wrap my head around solving this simple problem in XSLT without coming up with a solution:

    I've got a long text string (bodyText) where I need to insert a CR/LF at every 75 characters.

    Can anyone come up with any good ideas on how to solve this?

    Best regards,
    Soeren Sprogoe

  • Petr Snobelt 923 posts 1535 karma points
    Aug 18, 2009 @ 14:19
    Petr Snobelt
    101

    If you need/want xslt solution then use xslt substring with check for file length, but easier will be add inline csharp function into your xslt. Similar to getRandom at http://our.umbraco.org/wiki/reference/xslt/snippets/getting-a-series-of-unique-random-numbers

  • Chris Koiak 700 posts 2626 karma points
    Aug 18, 2009 @ 14:34
    Chris Koiak
    1

    The function would be something like....

     <msxsl:script language="c#" implements-prefix="randomTools">
       
    <msxsl:assembly href="../bin/umbraco.dll"/>
        <![CDATA[
    public static string InsertCrLf(string originalString) {
    string strMain = originalString;
    int len = strMain.Length;        
    string smallString = "";
    string newString = "";
    ArrayList myArray = new ArrayList();        

    while (len > 80)
    {
        smallString = strMain.Substring(0, 80);
        strMain = strMain.Substring(80);
       
        newString +=  smallString + "YOUR ADDED TEXT";
       len = strMain.Length;
    }

    newString += smallString;

    return newString;
    ]]>
     
    </msxsl:script>
    </xsl:stylesheet>

    If I were you though I would bundle it up into an xslt extension so it's easily used next time.

  • Soeren Sprogoe 575 posts 259 karma points
    Aug 18, 2009 @ 15:23
    Soeren Sprogoe
    1

    Thanks a lot to the both of you!

    Using both your suggestions I was able to construct this little function myself, that inserts a linebreak at the nearest space for every 75 characters:

    <msxml:script implements-prefix='MyFunc' language='CSharp'>
    <![CDATA[
    public static string InsertCrLf(string s) {
    string retval = "";
    string[] arr = s.Split(' ');
    foreach (string part in arr)
    {
    if ((retval.Length - retval.LastIndexOf("\n")) + part.Length >= 75)
    {
    retval = retval + " \n" + part;
    }
    else
    {
    retval = retval + " " + part;
    }
    }
    return retval;
    }
    ]]></msxml:script>

    And just in case you are wondering why on earth I need this: When constructing newsletters with low spam scores, you need to insert a line break at every 76 characters or less.

    /SoerenS

Please Sign in or register to post replies

Write your reply to:

Draft