IT Blog

  • Blog
  • Technology
    • Technology
    • Architecture
    • CMS
    • CRM
    • Web
    • DotNET
    • Python
    • Database
    • BI
    • Program Language
  • Users
    • Login
    • Register
    • Forgot Password?
  • ENEN
    • 中文中文
    • ENEN
DotNET
DotNET

Extend some useful string functions in C#

Add some useful extension methods for string manipulations in C#. Make coding more elegent, interesting and productive. string.ToBoolean(); string.ToInt(); string.RemoveSufix(string suffix); string.RemovePrefix(string prefix); string.Remove(string toBeRemoved); string.RemoveSpace(); string.RemoveWhiteSpace();   /// <summary> /// Accept string value: "true", "t", "1" as true, all others will be evaluated as false. /// </summary> /// <returns></returns> public static bool ToBoolean(this string value) { if (string.IsNullOrEmpty(value)) return false; switch (value.Trim().ToLower()) { case "true": return true; case "t": return true; case "1": return true; case "0": return false; case "false": return false; case "f": return false; case "": return false; default: return false; //throw new InvalidCastException("You can't cast that value to a bool!"); } } /// <summary> /// Convert a string to int with default value /// </summary> /// <returns></returns> public static int ToInt(this string value) { if (string.IsNullOrEmpty(value)) return 0; int.TryParse(value, out int i); return i; } /// <summary> /// Remove string suffix /// </summary> /// <param name="suffix"></param> /// <returns></returns> public static string RemoveSufix(this string value, string suffix) { if (value.EndsWith(suffix)) { value.Substring(0, value.Length - suffix.Length); } return value; } /// <summary> /// Remove string prefix /// </summary> /// <param name="prefix"></param> /// <returns></returns> public static string RemovePrefix(this string value, string prefix) { if (value.StartsWith(prefix)) { value.Substring(prefix.Length); } return value; } /// <summary> /// Remove all spaces from a string /// </summary> /// <returns></returns> public static string RemoveSpace(this string value) { return value.Replace(" ", string.Empty); } /// <summary> /// Remove all white spaces from a string, including " ", \t, \r, \n /// </summary> /// <returns></returns> public static string RemoveWhiteSpace(this string value) { return value.Replace(" ", string.Empty) .Replace("\t",…

2020-09-24 0 Comments 1189 Views 1 Like IT Team Read more
DotNET

Unicode to Chinese conversion notes

Unicode expressed like "\u4a44". Chinese words located from 0x3400 to 0x9fa5, including simplified and traditional words. Online tool: Unicode to Chinese covnerter C# Stores unicode data as a string, for each unicode in a string lookup the string by hex or integer number to get the right characters to replace them in the string. string ZHTable = "㐀㐁㐂㐃㐄㐅㐆㐇㐈㐉㐊㐋㐌㐍㐎㐏㐐... ...";   private string GetChar(string unicode) { unicode = unicode.Replace("\\u", ""); var code = Convert.ToInt32(unicode, 16); return ZHTable[code - 13312].ToString(); } var matches = Regex.Matches(text, @"\\u[a-f0-9]{4}"); string result = text; if (matches.Count > 0) { foreach (var m in matches) { var key = m.ToString(); result = result.Replace(key, GetChar(m.ToString())); } }   public string ToChinese(string text) { var matches = Regex.Matches(text, @"\\u[a-f0-9]{4}"); string result = text; if (matches.Count > 0) { foreach (var m in matches) { var key = m.ToString(); result = result.Replace(m.ToString(), GetChar(key)); } } return result; } PHP Stores unicode data in a dictionary like array, for each unicode in a string look up the dictionary to get the right characters to replace them in the string. $unicodedata = [ ... ... 0x3437 => '㐷', 0x3438 => '㐸', 0x3439 => '㐹', 0x343a => '㐺', 0x343b => '㐻', 0x343c => '㐼', ... ... ]; for number calculate as power of 16; for a-f, convert to ascii code - 87, so as a=10, f=15, then calculate as power of 16; for hex letter only has a-f, other than that throw exception. if($this->is_number($u[$i])){ $val += $u[$i] * pow(16, 3-$i); } elseif($this->is_hexletter($u[$i])){ $val += ord($u[$i])-87 * pow(16,3-$i); } to match all unicode, which…

2020-09-18 0 Comments 822 Views 0 Like IT Team Read more
DotNET

Accessing private fields in C#

Based OO principles the private fields should not be accessd by anything outside of the object. However, for some reason we have to access the private fields, a good example is unit testing. With dotnet reflection we could access any fields, members in an object. The accessibility is controled by BindingFlags, specify proper bindingFlags we can access all private fields in a class. To access the private fields in base class we need to add one more level of the type with BaseType. Here is the extension method to get the value of a public and private field in an instance. public static T GetFieldValue<T>(this object obj, string name) { var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; var field = obj.GetType().GetField(name, bindingFlags); if (field == null) field = obj.GetType().BaseType.GetField(name, bindingFlags); //father else if (field == null) field = obj.GetType().BaseType.BaseType.GetField(name, bindingFlags); //granpa else if (field == null) field = obj.GetType().BaseType.BaseType.BaseType.GetField(name, bindingFlags); //father of granpa return (T)field?.GetValue(obj); }  2,150 total views

2020-09-03 0 Comments 743 Views 0 Like IT Team Read more
DotNET

Crawler - Split column

Problem The second line contains pingying and alias. html code: Zhōngfǔ&nbsp;&nbsp;&nbsp;肺之募穴 First try get data roughly: alias = p.Select(Selectors.XPath("//span[@style]"))?.Value.Replace("&nbsp;", " "); Result: Zhōngfǔ   肺之募穴 Split the alias column in MySQL: UPDATE `xuewei` set pingying=substring_index(alias,' ',1); UPDATE `xuewei` set bieming=substring_index(alias,' ',-1); Split the column in process: alias = p.Select(Selectors.XPath("//span[@style]"))?.Value.Replace("&nbsp;", " "); var arr = alias.Split(' '); pingying = arr[0]; alias = arr[arr.Length-1]; //get last item in the array for the space in between is uncertain. Save to database: await conn.ExecuteAsync( $"INSERT IGNORE INTO xuewei (name,pingying,alias,position,anatomy,indication,operation,imagegeneral,imagepoint) VALUES " + $"('{data.Name}', '{data.Pingying}', '{data.Alias}', '{data.Position}', '{data.Anatomy}', '{data.Indication}', '{data.Operation}', '{data.ImageGeneral}', '{data.ImagePoint}');");  1,953 total views

2020-05-18 0 Comments 700 Views 0 Like IT Team Read more
DotNET

Crawler - get data from unwrapped html content

Content data on webpage: It's html code looks like this: Parsing data using regular expression with named group. Use foreach loop to avoid the order change on page. Do not use the text value from DOM function/property, because the text value does not contain html tag, which gives you the necessary mark on data.  14,070 total views,  5 views today

2020-05-17 3 Comments 3403 Views 0 Like IT Team Read more
DotNET

String concatenation in c# and php

C# Using + operator Console.WriteLine("Hello" + " " + "String " + "!"); String Interpolation string author = "Mahesh Chand"; string book = "C# Programming"; string bookAuthor = $"{author} is the author of {book}."; String.Concatenate() method string fName = "Mahesh"; string lName = "Chand"; string Name = string.Concat(fName, lName); string[] authors = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar "}; string arrayStr = string.Concat(authors); String.Join() method int[] intArray = { 1, 3, 5, 7, 9 }; String seperator = ", "; string result = "Int, "; result += String.Join(seperator, intArray); // Using String.Join(String, String[], int int) // Let's concatenate first two strings of the array String[] arr2 = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar " }; String seperator2 = ", "; string result2 = "First Author, "; result2 += String.Join(seperator2, arr2, 1, 2); Console.WriteLine($"Result: {result2}"); String.Format() method string date = String.Format("Today's date is {0}", DateTime.Now); StringBuilder.Append() method builder.Append(", "); PHP Using . operator $b = "Hello " . "World!"; // slow String Interpolation $a = '3'; echo "qwe{$a}rty"; // double quote echo "Result: " . ($a + 3); // result 6 "{$str1}{$str2}{$str3}"; // one concat = fast   $str1. $str2. $str3;    // two concats = slow //Use double quotes to concat more than two strings instead of multiple '.' operators.  PHP is forced to re-concatenate with every '.' operator. $logMessage = "A {$user->type} with e-mailaddress {$user->email} has performed {$action} on {$subject}." Using printf() $logMessage = sprintf('A %s with email %s has performed %s on %s.', $user->type, $user->email, $action, $subject);    2,762 total views,  10 views today

2020-04-29 0 Comments 1046 Views 0 Like IT Team Read more
Chinese (Simplified) Chinese (Simplified) Chinese (Traditional) Chinese (Traditional) English English French French German German Japanese Japanese Korean Korean Russian Russian
Newest Hotspots Random
Newest Hotspots Random
Rich editor not working Making web page scroll down automatically Getting data from Dapper result All Unicode Chars How to keep and display contact form 7 data Common Regular Expressions
CSS Tricks Getting data from Dapper result 手机邮件设定 Product Catalogue plugin issue fixes The events calendar - event title location How to auto-move to the bottom of a block
Categories
  • Architecture
  • BI
  • C#
  • CSS
  • Database
  • DotNET
  • Hosting
  • HTML
  • JavaScript
  • PHP
  • Program Language
  • Python
  • Security
  • SEO
  • Technology
  • Web
  • Wordpress

COPYRIGHT © 2021 Hostlike IT Blog. All rights reserved.

This site is supported by Hostlike.com