working on it ...

Filters

Explore Public Snippets

Sort by

Found 17k snippets matching: string

    public by MarcoDeMagistris modified Oct 3, 2013  558329  63  7  0

    Converts Unicode string to Ansi String

    Converts Unicode string to Ansi String
    public static string ConvertUnicodeToAnsi(String s)
            {
                /// <summary>
                /// Description: Converts Unicode string to Ansi String
                ///              
                /// </summary>
                /// <exception cref="ArgumentNullException"></code></exception>
                /// <exception cref="EncoderExceptionFallback"></exception>
                /// <exception cref="DecoderExceptionFallback"></exception>
                /// <exception cref="ArgumentException"></exception>
                try
                {
                    byte[] unicodeBytes = Encoding.Unicode.GetBytes(s);
                    byte[] ansiBytes = Encoding.Convert(Encoding.Unicode, Encoding.Default, unicodeBytes);
                    return Encoding.Default.GetString(ansiBytes).ToString();
                }
                catch {
                    throw;
                }
            }

    public by cghersi modified Jan 31, 2014  474486  4  7  0

    C#: Parse a comma separated string into a collection of numeric items

    This method can be used with any separator you need, just setting the 'separator' input
    public static List<long> ParseIntoListOfLongs(string content, char separator = ',')
    {
        List<long> ids = new List<long>();
    
        if (string.IsNullOrEmpty(content))
            return ids;
    
        string[] strIds = content.Split(separator);
        foreach (string str in strIds)
        {
            long id = -1;
            if (long.TryParse(str, out id))
            {
                if (id > 0)
                    ids.Add(id);
            }
        }
    
        return ids;
    }
    

    public by lbottaro modified Dec 10, 2014  475627  5  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by cghersi modified Oct 14, 2014  369280  3  6  3

    How to prettify a number with thousands or millions

    Prepares a pretty version of the given number, with the ability to match the right plural/singular form for English text
    public static string PaintNumber(int number, string followingText = "", bool numberInBold = false)
    {
      string content = String.Format("{0:N0}", number);
      if (number >= 10000)
      {
        double numberInThousands = number / 1000.0;
        if (numberInThousands < 100)
          content = String.Format("{0:N0}k", numberInThousands);
        else
          content = String.Format("{0:0.#}M", numberInThousands / 1000.0);
      }
      if (number >= 1000000)
      {
        double numberInMillions = number / 1000000.0;
        if (numberInMillions < 100)
          content = String.Format("{0:N0}M", numberInMillions);
        else
          content = String.Format("{0:0.#}B", numberInMillions / 1000.0);
      }
    
      if (numberInBold)
        content = "<b>" + content + "</b>";
    
      if (!string.IsNullOrEmpty(followingText))
        content += " " + followingText + (number != 1 ? "s" : "");
    
      return content;
    }
    

    public by zenitramPRO modified May 4, 2016  404136  3  5  1

    Adding an Element in an Array using a Function.

    Arrays of Objects Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects. Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Person objects, similar
    // Our person constructor
    function Person (name, age) {
        this.name = name;
        this.age = age;
    }
    
    // Now we can make an array of people
    var family = new Array();
    family[0] = new Person("alice", 40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle", 8);
    // add the last family member, "timmy", who is 6 years old
    family[3] = new Person("timmy", 6);
                                                    

    public by cghersi modified Aug 5, 2014  290115  1  6  0

    How to simply compute the MD5 hash of a given string, being sure to have the same results retrieved by HASH method of MS SQL Server

    Returns the MD5 hash of the given string
    public static String computeMD5Hash(String input) {
    	if (isNullOrEmpty(input))
    		return "";
    	byte[] bytesOfMessage = null;
    	try {
    		bytesOfMessage = input.getBytes("UTF-16LE");
    	} catch (UnsupportedEncodingException e) {
    		log.error("Cannot support UTF-8 encoding due to " + e, e);
    		return "";
    	}
    	MessageDigest md = null;
    	try {
    		md = MessageDigest.getInstance("MD5");
    	} catch (NoSuchAlgorithmException e) {
    		log.error("Cannot support MD5 algorithm due to " + e, e);
    		return "";
    	}
    	byte[] thedigest = md.digest(bytesOfMessage);
    	return printHexByteArray(thedigest);
    }

    public by cghersi modified Jan 10, 2017  289539  1  8  0

    How to read a file into a string in Java

    This simple snippet reads a file and put the content into a returned string
    private static String readFileAsString(String filePath) throws java.io.IOException{
    
    	StringBuffer fileData = new StringBuffer(1000);
    	BufferedReader reader = new BufferedReader(new FileReader(filePath));
    	char[] buf = new char[1024];
    	int numRead=0;
    	while((numRead=reader.read(buf)) != -1){
    		String readData = String.valueOf(buf, 0, numRead);
    		fileData.append(readData);
    		buf = new char[1024];
    	}
    
    	reader.close();
    	return fileData.toString();
    }            

    public by marksimon232 modified Jul 6, 2015  282994  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by pan modified Oct 14, 2014  245239  2  5  0

    Replace all occurrences of a string in DB

    Searches and replaces all of occurrences of a string in all tables and all fields of the given Database
    <?php
    /**
    * @kudos http://stackoverflow.com/a/10182498
    */
     
    header("Content-Type: text/plain");
    
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    $string_to_replace  = 'old.example.com';
    $new_string = 'new.example.com';
    
    // Connect to database server
    mysql_connect($host, $username, $password);
    
    // Select database
    mysql_select_db($database);
    
    // List all tables in database
    $sql = "SHOW TABLES FROM ".$database;
    $tables_result = mysql_query($sql);
    
    if (!$tables_result) {
        echo "Database error, could not list tables\nMySQL error: " . mysql_error();
        exit;
    }
    
    echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
    while ($table = mysql_fetch_row($tables_result)) {
        echo "Table: {$table[0]}\n";
        $fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
        if (!$fields_result) {
            echo 'Could not run query: ' . mysql_error();
            exit;
        }
        if (mysql_num_rows($fields_result) > 0) {
            while ($field = mysql_fetch_assoc($fields_result)) {
                if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
                    echo "  ".$field['Field']."\n";
                    $sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
                    mysql_query($sql);
                }
            }
            echo "\n";
        }
    }
    
    mysql_free_result($tables_result);

    public by zonaro modified Oct 23, 2015  205192  1  7  0

    Image toBase64 String

    Extension method to convert a System.Drawing.Image to Base64 String
    public static string toBase64(this System.Drawing.Image OriginalImage)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  OriginalImage.Save(ms, OriginalImage.RawFormat);
                  byte[] imageBytes = ms.ToArray();
                  return Convert.ToBase64String(imageBytes);
              }
          }
    
    • Public Snippets
    • Channels Snippets