working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,271 snippets matching: trim

    public by JMichaelTX  351575  2  3  0

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley)

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley): trimThis Function AS.applescript
    ###BEGIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #    trimThis()      Trim (remove) Characters from Left and/or Right of String
    #
    #    Ver 1.1          2016-02-25
    #    AUTHOR:          Shane Stanley
    #                     (minor revisions by JMichaelTX)
    #    REF:             MacScripter / Trim [Remove Spaces]
    #                     http://macscripter.net/viewtopic.php?pid=182209#p182209
    #  PARAMETERS:
    #    • pstrCharToTrim    : A list of characters to trim, or true to use default
    #    • pstrSourceText    : The text to be trimmed
    #    • pstrTrimDirection : Direction of Trim left, right or any value for full
    ###——————————————————————————————————————————————————————————————————————————————————
    
    on trimThis(pstrSourceText, pstrCharToTrim, pstrTrimDirection)
      
      --- SET CHARACTERS TO TRIM ---
      
      if pstrCharToTrim = missing value or pstrCharToTrim = true then
        -- SPACE, TAB, RETURN, newline characters (U+000A–U+000D, U+0085)
        -- Equiv to: ASCII character 10, return, ASCII character 0
        
        set setToTrim to current application's NSCharacterSet's whitespaceAndNewlineCharacterSet()
      else
        set setToTrim to current application's NSCharacterSet's characterSetWithCharactersInString:pstrCharToTrim
      end if
      
      set anNSString to current application's NSString's stringWithString:pstrSourceText
      
      --- TRIM STRING BASED ON REQUESTED DIRECTION ---
      
      if pstrTrimDirection = left then -- FROM LEFT SIDE OF STRING
        
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet())
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringFromIndex:(theRange's location)
        
      else if pstrTrimDirection = right then -- FROM RIGHT SIDE OF STRING
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet()) options:(current application's NSBackwardsSearch)
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringToIndex:(theRange's location)
        
      else -- FROM BOTH SIDES OF STRING
        set anNSString to anNSString's stringByTrimmingCharactersInSet:setToTrim
      end if
      
      return anNSString as text
    end trimThis
    ###END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    

    public by mporru  15721  221  8  2

    Trim, TrimStart, TrimEnd methods in java

    public static String TrimEnd(String input, String charsToTrim)
    	{
    		return input.replaceAll("[" + charsToTrim + "]+$", "");		
    	}	
    	
    	public static String TrimStart(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+", "");	
    	}
    
    	public static String Trim(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+|[" + charsToTrim + "]+$", "");	
    	}

    public by cghersi  3915  10  8  2

    C#: How to shorten an URL using a third party service like Bitly, Isgd, Tinyurl or Trim

    This class provides the capability to shorten an URL using one of the given third party services
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Xml;
    
    public class ShortenURL
    {
        public enum ShortURLProvider
        {
            Bitly = 0,
            Isgd = 1,
            Tinyurl = 2,
            Trim = 3,
        }
    
    
        /// <summary>
        /// try to use different services to shorten the given url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="eService"></param>
        /// <returns></returns>
        public static string DoShortenURL(string url, ShortURLProvider eService)
        {
            // return empty strings if not valid  
            if (!IsValidURL(url))
                return string.Empty;
    
            string requestUrl = string.Format(GetRequestTemplate(eService), url);
            WebRequest request = HttpWebRequest.Create(requestUrl);
            request.Proxy = null;
            string strResult = null;
            try
            {
                using (Stream responseStream = request.GetResponse().GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.ASCII);
                    strResult = reader.ReadToEnd();
                    if (!IsValidURL(strResult))
                        return string.Empty;
                }
            }
            catch (Exception)
            {
                strResult = url;
            }
    
            // if converted is longer than original, return original  
            if (strResult.Length > url.Length)
                strResult = url;
    
            //if the previous service didn't work, try Tr.im:
            if (strResult.CompareTo(url) == 0)
                strResult = GetShortURLbyXML(url);
    
            return strResult;
        }
    
    
        /// <summary>
        /// validation of the url
        /// </summary>
        /// <param name="strurl"></param>
        /// <returns></returns>
        public static bool IsValidURL(string strurl)
        {
            return (strurl.ToLower().StartsWith("http://") || strurl.StartsWith("https://"));
        }
    
    
        /// <summary>
        /// Request template for URL
        /// </summary>
        /// <param name="eService"></param>
        /// <returns></returns>
        private static string GetRequestTemplate(ShortURLProvider eService)
        {
            string strRequest = string.Empty;
            switch (eService)
            {
                case ShortURLProvider.Isgd:
                    strRequest = "http://is.gd/api.php?longurl={0}";
                    break;
                case ShortURLProvider.Bitly:
                    strRequest = "http://bit.ly/api?url={0}"; ;
                    break;
                case ShortURLProvider.Tinyurl:
                    strRequest = "http://tinyurl.com/api-create.php?url={0}";
                    break;
                case ShortURLProvider.Trim:
                    strRequest = "http://tr.im/api/trim_url.xml?url={0}";
                    break;
                default:
                    break;
            }
    
            return strRequest;
        }
    
    
        /// <summary>
        /// shorten the url using Tr.im service
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        protected static string GetShortURLbyXML(string url)
        {
            //prepare the request to the remote service
            //Note: Tr.im wants the url NOT HttpEncoded!!!
            string trimUrl = string.Format(GetRequestTemplate(ShortURLProvider.Trim), url);
            WebClient client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            string resultUrl = string.Empty;
            XmlDocument result = new XmlDocument();
    
            try
            {
                //send a request to tr.im
                Stream data = client.OpenRead(trimUrl);
    
                //load the response in an XML document
                result.Load(data);
    
                data.Close();
            }
            catch
            {
                return resultUrl;
            }
    
            //parse the XML response
            XmlNode statusNode = result.SelectSingleNode("/trim/status");
            string status = string.Empty;
            if (statusNode != null)
                status = statusNode.Attributes["result"].InnerText;
    
            //retrieve the tinyurl
            if (status.CompareTo("OK") == 0)
            {
                XmlNode urlNode = result.SelectSingleNode("/trim/url");
                if (urlNode != null)
                    resultUrl = urlNode.InnerText;
            }
    
            return resultUrl;
        }
    }
    

    public by cghersi  2496  1  7  2

    Trim starting spaces and tabs from a block of text

    /** * Removes the starting tabs or spaces from each line of the given text: * first of all this methods computes the common number of tabs or spaces for all the single lines of he * given input text; then trims the common number of such characters, if needed. * @param text text to trim * @return the trimmed text */
    public static String trimStartingTabsOrSpaces(String text) {
    	if (Utils.isNullOrEmpty(text))
    		return text;
    	
    	//split into lines:
    	String[] lines = text.split(LINE_SEPARATOR);
    
    	//count the number of tabs and spaces at the start of each line:
    	int numOfTabs = Integer.MAX_VALUE;
    	int numOfSpaces = Integer.MAX_VALUE;
    	for (String line : lines) {
    		//check the number of tabs in the current line:
    		int curNumOfTabs = countStartingChars(line, '\t');
    		
    		//refresh the minimum number of tabs of the entire text:
    		if (curNumOfTabs < numOfTabs)
    			numOfTabs = curNumOfTabs;
    		
    		//check the number of spaces in the current line:
    		int curNumOfSpaces = countStartingChars(line, ' ');
    			
    		//refresh the minimum number of spaces of the entire text:
    		if (curNumOfSpaces < numOfSpaces)
    			numOfSpaces = curNumOfSpaces;			
    		
    		if ((numOfTabs == 0) && (numOfSpaces == 0))
    			break;
    	}
    	
    	//if a positive number of tabs have been found in all the lines, 
    	//trim all the lines of the actual minimum common number of tabs:
    	if (numOfTabs > 0) 
    		return trimStartingChar(lines, numOfTabs);
    	
    	//if a positive number of spaces have been found in all the lines, 
    	//trim all the lines of the actual minimum common number of spaces:
    	if (numOfSpaces > 0) 
    		return trimStartingChar(lines, numOfSpaces);
    	
    	//otherwise, leave the given input untouched:
    	return text;
    }
    
    
    private static int countStartingChars(String line, char c) {
    	if (Utils.isNullOrEmpty(line))
    		return 0;
    	for (int pos = 0; pos < line.length(); pos++) {
    		if (line.charAt(pos) != c)
    			return pos;
    	}
    	return line.length();
    
    
    
    private static String trimStartingChar(String[] lines, int numOfCharsToTrim) {
    	StringBuilder str = new StringBuilder();
    	for (String line : lines) {
    		str.append(line.substring(numOfCharsToTrim));
    		str.append(LINE_SEPARATOR);
    	}
    	return str.toString();
    }

    public by cghersi  2742  0  7  0

    How to trim trailing chars and tabs from a given text

    Removes the starting tabs or spaces from each line of the given text: first of all this methods computes the common number of tabs or spaces for all the single lines of the given input text; then trims the common number of such characters, if needed.
            public static string TrimStartingTabsOrSpaces(string text) 
            {
    		    if (string.IsNullOrWhiteSpace(text))
    			    return text;
    		
    		    //split into lines:
                log.DebugFormat("Splitting: {0}", text);
                int posOfSlashN = text.IndexOf(LINE_SEPARATOR);
                if (posOfSlashN < 0)
                {
                    //cannot find line separator, check if at least '\r' is found:
                    log.Debug("Cannot find \\n, trying to find \\r");
                    int posOfSlashR = text.IndexOf('\r');
                    if (posOfSlashR >= 0)
                    {
                        log.Debug("Found \\r, replacing with line correct separator");
                        text = text.Replace("\r", "\r\n");
                    }
                }
    
    		    string[] lines = text.Split(LINE_SEPARATOR);
                log.DebugFormat("found {0} lines", lines.Length);
    
    		    //count the number of tabs and spaces at the start of each line:
    		    int numOfTabs = int.MaxValue;
                int numOfSpaces = int.MaxValue;
    		    foreach (string line in lines) 
                {
                    if (line.IsNullOrWhiteSpaceOrEOF())
                        continue;
    
    			    //check the number of tabs in the current line:
    			    int curNumOfTabs = CountStartingChars(line, '\t');
    			
    			    //refresh the minimum number of tabs of the entire text:
    			    if (curNumOfTabs < numOfTabs)
    				    numOfTabs = curNumOfTabs;
    			
    			    //check the number of spaces in the current line:
    			    int curNumOfSpaces = CountStartingChars(line, ' ');
    			
    			    //refresh the minimum number of spaces of the entire text:
    			    if (curNumOfSpaces < numOfSpaces)
    				    numOfSpaces = curNumOfSpaces;			
    			
    			    if ((numOfTabs == 0) && (numOfSpaces == 0))
    				    break;
    		    }
    		
    		    //if a positive number of tabs have been found in all the lines, 
    		    //trim all the lines of the actual minimum common number of tabs:
    		    if (numOfTabs > 0) 
    			    return TrimStartingChar(lines, numOfTabs);
    		
    		    //if a positive number of spaces have been found in all the lines, 
    		    //trim all the lines of the actual minimum common number of spaces:
    		    if (numOfSpaces > 0) 
    			    return TrimStartingChar(lines, numOfSpaces);
    		
    		    //otherwise, leave the given input untouched:
    		    return text;
    	    }
            private static char LINE_SEPARATOR = '\n';
            private static int CountStartingChars(string line, char c)
            {
                if (string.IsNullOrWhiteSpace(line))
                    return 0;
                for (int pos = 0; pos < line.Length; pos++)
                {
                    if (line[pos] != c)
                        return pos;
                }
                return line.Length;
            }
            private static string TrimStartingChar(string[] lines, int numOfCharsToTrim) 
            {
    		    StringBuilder str = new StringBuilder();
    		    foreach (string line in lines) 
                {
                    if (line.IsNullOrWhiteSpaceOrEOF())
                        str.Append(line);
                    else
                    {
                        str.Append(line.Substring(numOfCharsToTrim));
                        log.DebugFormat("end of line: {0} {1}", PrintChar(line[line.Length - 2]), PrintChar(line[line.Length - 1]));
                    }
                    str.Append(LINE_SEPARATOR);
    		    }
                return str.ToString();
    	    }
            private static char PrintChar(char c)
            {
                switch (c)
                {
                    case '\r': return 'r';
                    case '\n': return 'n';
                    default: return c;
                }
            }

    public by cghersi  1599  0  4  0

    Trim a string with optional ellipsis

    Removes the exceeding part of the given string, replacing it with three dots.
    public static string TrimWithEllipsis(string input, int maxChars)
    {
      if (input == null)
        return null;
      string res = input.Trim();
      if (res.Length > (maxChars - 3))
        return res.Substring(0, maxChars - 3) + "...";
      else
        return res;
    }
    

    public by snip2code  2959  0  4  0

    Trim a string with ellipsis

    This is the simplest way to trim a string to the given length. If trimmed, the last part of the string is replaced with ellipsis
    public static String trimWithDots(String input, int maxLen) {
    	if (isNullOrEmpty(input))
    		return "";
    	if (input.length() > (maxLen - 3))
    		return input.substring(0, maxLen - 3) + "...";
    	else
    		return input;
    }

    public by carmeloruota  2039  0  4  0

    trim IOS

    NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                      [NSCharacterSet whitespaceCharacterSet]];
                                      
    // per rimuovere anche newLine usare whitespaceAndNewlineCharacterSet

    public by raminhos  1812  1  6  0

    Just Trim

    function justtrim($string, $lenght){
      //$lenght = 22;
      $str_to_count = html_entity_decode($string);
      if (strlen($str_to_count) <= $lenght) {
        return $string;
      }
      $s2 = substr($str_to_count, 0, $lenght - 3);
      $s2 .= "..";
      return $s2;
    }

    public by Geometry  749  0  5  0

    Convolve: Convolves an array with the given kernel.

    Convolves an array with the given kernel. A floating number array. A convolution kernel. If true the resulting array will be trimmed to have the same length as the input array. Default is false.
    /// <summary>
    /// Convolves an array with the given kernel.
    /// </summary>
    /// 
    /// <param name="a">A floating number array.</param>
    /// <param name="kernel">A convolution kernel.</param>
    /// <param name="trim">
    ///   If <c>true</c> the resulting array will be trimmed to
    ///   have the same length as the input array. Default is false.</param>
    ///   
    public static double[] Convolve(this double[] a, double[] kernel, bool trim)
    {
        double[] result;
        int m = (int)System.Math.Ceiling(kernel.Length / 2.0);
    
        if (trim)
        {
            result = new double[a.Length];
    
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = 0;
                for (int j = 0; j < kernel.Length; j++)
                {
                    int k = i - j + m - 1;
                    if (k >= 0 && k < a.Length)
                        result[i] += a[k] * kernel[j];
                }
            }
        }
        else
        {
            result = new double[a.Length + m];
    
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = 0;
                for (int j = 0; j < kernel.Length; j++)
                {
                    int k = i - j;
                    if (k >= 0 && k < a.Length)
                        result[i] += a[k] * kernel[j];
                }
            }
        }
    
        return result;
    }
    • Public Snippets
    • Channels Snippets