Author : MD TAREQ HASSAN | Updated : 2021/03/22
String syntax
// Empty string
var emptyText = String.Empty; // zero-length string ""
// Literal string
var sampleText = "This is a string";
// Verbatim string: use @
var path = @"c:\test\foo.txt"; // rather than "c:\\test\\foo.txt"
// Interpolation
var x = 10;
var sampleTextByInterpolation = $"Value of x is {x}";
Split
/*
public string[] Split(separator, StringSplitOptions options)
Seperator => Char: ' ', String: " ", Char[], String[]
if Seperator is null or empty => white-space characters are assumed to be the delimiters
Enum StringSplitOptions: None/RemoveEmptyEntries
StringSplitOptions.None : returned array will contain String.Empty ("") elements
StringSplitOptions.RemoveEmptyEntries : returned array will not contain String.Empty ("") elements
*/
var foo = "..."
var words = foo.Split(' '); // seperator char
var words = foo.Split(",") // seperator string
char[] delimiterChars = { ' ', ',', '.', '\t' }; // seperator char array
var words = foo.Split(delimiterChars);
string[] stringSeparators = { ";", "." }; // seperator string array
var words = foo.Split(stringSeparators , StringSplitOptions.RemoveEmptyEntries);
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
Split details
var substrings = Regex.Split(input, pattern);
Regex regex = new Regex("-"); // Split on hyphens
var substrings = regex.Split("plum--pear");
/*
The Regex.Split methods are similar to the String.Split(Char[]) method,
except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters.
*/
See: Splitting String with RegEx
Join
/*
String.Join<T>(String, IEnumerable<T>);
String.Join<T>(String, Enumerable.Where<T>(lambda));
public static string Join (string separator, string[] value);
public static string Join (string separator, params object[] values);
public static string Join (string separator, string[] value, int startIndex, int count);
If separator is null, an empty string (String.Empty) is used instead.
If any member of values is null, an empty string is used instead.
*/
var result = String.Join("|", 1, 2, 3);
var foo = new string[] {"bar", "baz"}
var result = String.Join("|", foo);
var result = String.Join("|", foo, 1, 2);
See: String.Join Method
String constructor
// Create a string from a character array
char[] chars = { 'w', 'o', 'r', 'l', 'd' };
string textFromCharArray = new string(chars);
// Create a string that consists of a character repeated 20 times.
string textWithSameCharMultipleTimes = new string('c', 20);
Empty check
String.IsNullOrEmpty(String); // static method
String.IsNullOrWhiteSpace(String); // static method
Readonly indexer
// String class has read only indexer
string str = "test";
char x = str[2]; // x = 's';
Substring
Substring(startIndex); // up to end
Substring(startIndex, endIndex);
String[] pairs = { "Color1=red", "Color2=green", "Color3=blue", "Title=Code Repository" };
foreach (var pair in pairs) {
int position = pair.IndexOf("=");
if (position < 0) {
continue;
}
var pre = pair.Substring(0, position);
var post = pair.Substring(position + 1);
}
Replace
/*
public string Replace (char oldChar, char newChar);
public string Replace (string oldValue, string newValue); // If newValue is null, all occurrences of oldValue are removed.
*/
String str = "1 2 3 4 5 6 7 8 9";
var foo = str.Replace(' ', ',') // "1,2,3,4,5,6,7,8,9"
string errString = "This docment uses 3 other docments to docment the docmentation";
string correctString = errString.Replace("docment", "document");
// static and instance methods
Regex.Replace(string[], pattern, replaceWith); // Regex.Replace(arr, @",", String.Empty);
Regex.Replace(overloads);
Contains
public bool Contains (string value);
Char to String
// interpolation
char ch = 'x';
string str = $"{ch}";
// string constructor
string str = new string(new char[] { 'x' });
// ToString()
char ch = 'x';
var str = ch.ToString();
// when char is int val
var val = 120;
string str = Char.ConvertFromUtf32(val); // x
String to Char
string str = "Hello";
char[] characters = str.ToCharArray();
// readonly indexer of string
var str = "hovermind";
var firstChar = str[0]; // h
Char Array to String
// string constructor
var charArray = new char[] { 'a', 'b', 'c' };
var str = new String(charArray);
Console.WriteLine(str);
var charArray = new char[] { 'a', 'b', 'c' };
var str = String.Join(" ", charArray);
Console.WriteLine(str); // "a b c"
String to Char Array
// string is char array
var str = "abcd";
foreach(var ch in str){
Console.WriteLine(ch);
}
// ToCharArray()
var str = "abcd";
var chars = str.ToCharArray();
foreach(var ch in chars){
Console.WriteLine(ch);
}
// read only indexer of string
for(var i = 0; i < str.Length; i++) {
var ch = str[i];
Console.WriteLine(ch);
}
Array to String
var str = String.Join(" ", new char[] { 'a', 'b', 'c' });
Console.WriteLine(str); // "a b c"
str = String.Join(" ", 'a', 'b', 'c');
Console.WriteLine(str); // "a b c"
str = String.Join(" ", new string[] { "hover", "mind" });
Console.WriteLine(str); // "hover mind"
str = String.Join(" ", "hover", "mind");
Console.WriteLine(str); // "hover mind"
str = String.Join("|", 1, 2, 3);
Console.WriteLine(str); // "1|2|3"
String to Word Array
var words = str.Split(seperator, StringSplitOptions options) // seperator => Char: ' ' / String: " " / Char[] / String[]
/*
if separator is null or "" => deault (white-space characters) will be used
StringSplitOptions.None => returned array contains both empty and non-empty items
StringSplitOptions.RemoveEmptyEntries => returned array contains only non-empty items
when using String[] as seperator => must use StringSplitOptions
*/
var str = "ab cd ef";
var words = str.Split(' '); // seperator: char
var words = str.Split(new char[] { ' ' }); // seperator: char array => method signature: Split(Char[])
var words = str.Split(" "); // seperator: string
// string array as seperators => method signature: Split(Char[], StringSplitOptions)
var words = str.Split(new string[] { " ", "|" }, StringSplitOptions.None); // when using string array => must use StringSplitOptions
foreach(var word in words){
Console.WriteLine(word);
}
String to List
List<string> words = myString.Split(" ").ToList()
List to String
//String.Join(string separator, IEnumerable<T> collection);
List<string> words = new List<string> { "hover", "mind" };
var str = String.Join(" ", words);
Console.WriteLine(str);
Dictionary to String
string str = string.Join(";", myDict.Select(kv => kv.Key + "=" + kv.Value).ToArray());
String to Dictionary
var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
Binary Digits as String
string binaryString = Convert.ToString(n, 2); // "110011010111"
int value = Convert.ToInt32("11001", 2)
JSON String With Interpolation
- To escape “
{
” or “}
”: use double curly braces{{
- To escape “
:
”: use double quotes twice""
Example: https://stackoverflow.com/a/43474880/4802664
var json = $@"{{""name"":""{name}""}}";
Return controller name and method name automatically
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
namespace API.Foo.Controllers
{
[ApiController]
[Route("api/foo")]
public class FooController : ControllerBase
{
[HttpGet("")]
public string Index()
{
return $@"{{ ""controller-name"" : ""{GetType().Name}"", ""method-name"" : ""{MethodBase.GetCurrentMethod().Name}"" }}";
}
[HttpGet("test")]
public string Test()
{
return $@"{{ ""controller-name"" : ""{GetType().Name}"", ""method-name"" : ""{MethodBase.GetCurrentMethod().Name}"" }}";
}
}
}