Chapter11:CommonStringOperations

No Comments

Section11.1:Formattingastring

UsetheString.Format()methodtoreplaceoneormoreitemsinthestringwiththestringrepresentationofa specified object:

String.Format(“Hello{0}Foo{1}”,”World”,”Bar”)//HelloWorldFooBar

Section11.2:Correctlyreversingastring

Mosttimeswhenpeoplehavetoreverseastring,theydoitmoreorlesslikethis:

char[]a=s.ToCharArray();

System.Array.Reverse(a);

stringr=newstring(a);

However, what these people don’t realize is that this is actually wrong. And I don’t mean because of the missing NULL check.

ItisactuallywrongbecauseaGlyph/GraphemeClustercanconsistoutofseveralcodepoints(aka.characters). To see why this is so, we first have to be aware of the fact what the term “character” actually means.

Reference:

Characterisanoverloadedtermthancanmeanmanythings.

Acodepointistheatomicunitofinformation.Textisasequenceofcodepoints.Eachcodepointisa number which is given meaning by the Unicode standard.

A grapheme is a sequence of one or more code points that are displayed as a single, graphical unit that a reader recognizes as a single element of the writing system. For example, both a and äare graphemes, but they may consist of multiple code points (e.g. ämay be two code points, one for the base character a followed by one for the diaresis; but there’s also an alternative, legacy, single code point representing this grapheme). Some code points are never part of any grapheme (e.g. the zero-width non-joiner, or directional overrides).

Aglyphisanimage,usuallystoredinafont(whichisacollectionofglyphs),usedtorepresentgraphemes or parts thereof. Fonts may compose multiple glyphs into a single representation, for example, if theabove äis a single code point, a font may chose to render that as two separate, spatially overlaid glyphs. For OTF, the font’s GSUB and GPOS tables contain substitution and positioning information to make this work. A font may contain multiple alternative glyphs for the same grapheme, too.

SoinC#,acharacterisactuallyaCodePoint.

Whichmeans,ifyoujustreverseavalidstringlikeLesMisérables,whichcanlooklikethis

strings=”LesMise\u0301rables”;

asasequenceofcharacters,youwillget:

selbaŕesiMseL

Asyoucansee,theaccentisontheRcharacter,insteadoftheecharacter.

Although string.reverse.reverse will yield the original string if you both times reverse the char array, this kind of reversal is definitely NOT the reverse of the original string.

You’llneedtoreverseeachGraphemeClusteronly.

So, if done correctly, you reverse a string like this:

privatestaticSystem.Collections.Generic.List<string>GraphemeClusters(strings)

{

System.Collections.Generic.List<string>ls=newSystem.Collections.Generic.List<string>();

System.Globalization.TextElementEnumeratorenumerator=

System.Globalization.StringInfo.GetTextElementEnumerator(s);

while(enumerator.MoveNext())

{

ls.Add((string)enumerator.Current);

}

returnls;

}

//this

(strings)

{privatestaticstringReverseGraphemeClusters

if(string.IsNullOrEmpty(s)||s.Length==1)

returns;

System.Collections.Generic.List<string>ls=GraphemeClusters(s); ls.Reverse();

returnstring.Join(“”,ls.ToArray());

}

publicstaticvoidTestMe()

{

strings=”LesMise\u0301rables”;

//s=”noël”;

stringr=ReverseGraphemeClusters(s);

//Thiswouldbewrong:

//char[]a=s.ToCharArray();

//System.Array.Reverse(a);

//stringr=newstring(a);

System.Console.WriteLine(r);

}

And-ohjoy-you’llrealizeifyoudoitcorrectlylikethis,itwillalsoworkforAsian/South-Asian/East-Asianlanguages (and French/Swedish/Norwegian, etc.)…

Section11.3:Paddingastringtoafixedlength

strings=”Foo”;

stringpaddedLeft=s.PadLeft(5); //paddedLeft=”             Foo”(padswithspacesbydefault)

stringpaddedRight=s.PadRight(6,’+’);//paddedRight=”Foo+++”

stringnoPadded=s.PadLeft(2); //noPadded=”Foo”(originalstringisnevershortened)

Section11.4:Gettingxcharactersfromtherightsideofa string

Visual Basic has Left, Right, and Mid functions that returns characters from the Left, Right, and Middle of a string. ThesemethodsdoesnotexistinC#,butcanbeimplementedwithSubstring().Theycanbeimplementedasan extension methods like the following:

publicstaticclassStringExtensions

{

///<summary>

///VBLeftfunction

///</summary>

///<paramname=”stringparam”></param>

///<paramname=”numchars”></param>

///<returns>Left-mostnumcharscharacters</returns>

publicstaticstringLeft(thisstringstringparam,intnumchars)

{

//HandlepossibleNullornumericstringparambeingpassed

stringparam+=string.Empty;

//Handlepossiblenegativenumcharsbeingpassed

numchars=Math.Abs(numchars);

//Validatenumcharsparameter

if(numchars>stringparam.Length)

numchars=stringparam.Length;

returnstringparam.Substring(0,numchars);

}

///<summary>

///VBRightfunction

///</summary>

///<paramname=”stringparam”></param>

///<paramname=”numchars”></param>

///<returns>Right-mostnumcharscharacters</returns>

publicstaticstringRight(thisstringstringparam,intnumchars)

{

//HandlepossibleNullornumericstringparambeingpassed

stringparam+=string.Empty;

//Handlepossiblenegativenumcharsbeingpassed

numchars=Math.Abs(numchars);

//Validatenumcharsparameter

if(numchars>stringparam.Length)

numchars=stringparam.Length;

returnstringparam.Substring(stringparam.Length-numchars);

}

///<summary>

///VBMidfunction-toendofstring

///</summary>

///<paramname=”stringparam”></param>

///<paramname=”startIndex”>VB-Stylestartindex,1stcharstartindex=1</param>

///<returns>Balanceofstringbeginningatstartindexcharacter</returns>

publicstaticstringMid(thisstringstringparam,intstartindex)

{

//HandlepossibleNullornumericstringparambeingpassed

stringparam+=string.Empty;

//Handlepossiblenegativestartindexbeingpassed

startindex=Math.Abs(startindex);

//Validatenumcharsparameter

if(startindex>stringparam.Length)

startindex=stringparam.Length;

//C#stringsarezero-based,convertpassedstartindex

returnstringparam.Substring(startindex-1);

}

///<summary>

///VBMidfunction-fornumberofcharacters

///</summary>

///<paramname=”stringparam”></param>

///<paramname=”startIndex”>VB-Stylestartindex,1stcharstartindex=1</param>

///<paramname=”numchars”>numberofcharacterstoreturn</param>

///<returns>Balanceofstringbeginningatstartindexcharacter</returns>

publicstaticstringMid(thisstringstringparam,intstartindex,intnumchars)

{

//HandlepossibleNullornumericstringparambeingpassed

stringparam+=string.Empty;

//Handlepossiblenegativestartindexbeingpassed

startindex=Math.Abs(startindex);

//Handlepossiblenegativenumcharsbeingpassed

numchars=Math.Abs(numchars);

//Validatenumcharsparameter

if(startindex>stringparam.Length)

startindex=stringparam.Length;

//C#stringsarezero-based,convertpassedstartindex

returnstringparam.Substring(startindex-1,numchars);

}

}

Thisextensionmethodcanbeusedasfollows:

stringmyLongString=”HelloWorld!”;

stringmyShortString=myLongString.Right(6);                                                                                                                 //”World!”stringmyLeftString=myLongString.Left(5);                                                                                                                 //”Hello”stringmyMidString1=myLongString.Left(4);                                                                                                                 //”loWorld”stringmyMidString2=myLongString.Left(2,3);                                                                                                                      //”ell”

Section11.5:CheckingforemptyStringusing String.IsNullOrEmpty()andString.IsNullOrWhiteSpace()

stringnullString=null;

stringemptyString=””;

stringwhitespaceString=”                     “;

stringtabString=”\t“;

stringnewlineString=”\n“;

stringnonEmptyString=”abc123″;

boolresult;

result=String.IsNullOrEmpty(nullString); //true

result=String.IsNullOrEmpty(emptyString); //true

result = String.IsNullOrEmpty(whitespaceString); //false

result=String.IsNullOrEmpty(tabString); //false

result=String.IsNullOrEmpty(newlineString); //false

result=String.IsNullOrEmpty(nonEmptyString); //false

result=String.IsNullOrWhiteSpace(nullString);                                   // true result=String.IsNullOrWhiteSpace(emptyString);                             // true result=String.IsNullOrWhiteSpace(tabString);   // true

result = String.IsNullOrWhiteSpace(newlineString);// true result = String.IsNullOrWhiteSpace(whitespaceString); // true result = String.IsNullOrWhiteSpace(nonEmptyString);// false

Section 11.6: Trimming Unwanted Characters Off the Start and/or End of Strings

String.Trim()

stringx=”                  HelloWorld!

stringy=x.Trim();//”HelloWorld!”

stringq=”{(Hi!*”;

stringr=q.Trim(‘(‘,’*’,'{‘);//”Hi!”

String.TrimStart()andString.TrimEnd()

stringq=”{(Hi*”;

stringr=q.TrimStart(‘{‘);//”(Hi*”

strings=q.TrimEnd(‘*’);                   //”{(Hi”

Section 11.7: Convert Decimal Number to Binary,Octal and Hexadecimal Format

  1. Toconvertdecimalnumbertobinaryformatusebase2

Int32Number=15;

Console.WriteLine(Convert.ToString(Number,2));           //OUTPUT:1111

2. Toconvertdecimalnumbertooctalformatusebase8

intNumber=15;

Console.WriteLine(Convert.ToString(Number,8));           //OUTPUT:17

3. Toconvertdecimalnumbertohexadecimalformatusebase16

varNumber=15;

Console.WriteLine(Convert.ToString(Number,16));              //OUTPUT:f

Section11.8:ConstructastringfromArray

TheString.JoinmethodwillhelpustoconstructastringFromarray/listofcharactersorstring.Thismethod accepts two parameters. The first one is the delimiter or the separator which will help you to separate each element in the array. And the second parameter is the Array itself.

Stringfromchararray:

stringdelimiter=”,”;

char[]charArray=new[]{‘a’,’b’,’c’};

stringinputString=String.Join(delimiter,charArray);

Output:a,b,cifwechangethedelimiteras””thentheoutputwillbecomeabc.

StringfromListofchar:

stringdelimiter=”|”;

List<char>charList=newList<char>(){‘a’,’b’,’c’};

stringinputString=String.Join(delimiter,charList);

Output:a|b|c

StringfromListofStrings:

stringdelimiter=””;

List<string>stringList=newList<string>() {“Ram”,”is”,”a”,”boy”}; stringinputString=String.Join(delimiter,stringList);

Output:Ramisaboy

String fromarrayofstrings:

stringdelimiter=”_”;

string[]stringArray=new[]{“Ram”,”is”,”a”,”boy”};

stringinputString=String.Join(delimiter,stringArray);

Output:Ram_is_a_boy

Section11.9:FormattingusingToString

Usually we are using String.Formatmethod for formatting purpose, the.ToStringis usually used for converting othertypestostring.WecanspecifytheformatalongwiththeToStringmethodwhileconversionistakingplace,So wecanavoidanadditionalFormatting.LetMeExplainhowitworkswithdifferenttypes;

Integertoformattedstring:

intintValue=10;

stringzeroPaddedInteger=intValue.ToString(“000”);//Outputwillbe”010″

stringcustomFormat=intValue.ToString(“Inputvalueis0”);//outputwillbe                                       “Inputvalueis 10”

doubletoformattedstring:

doubledoubleValue=10.456;

stringroundedDouble=doubleValue.ToString(“0.00”);//output10.46

stringintegerPart=doubleValue.ToString(“00”);                             //output10

stringcustomFormat=doubleValue.ToString(“Inputvalueis0.0”);                              //Inputvalueis10.5

FormattingDateTimeusingToString

DateTimecurrentDate=DateTime.Now;//               {7/21/20167:23:15PM}

stringdateTimeString=currentDate.ToString(“dd-MM-yyyyHH:mm:ss”);//”21-07-201619:23:15″

stringdateOnlyString=currentDate.ToString(“dd-MM-yyyy”);//”21-07-2016″

stringdateWithMonthInWords= currentDate.ToString(“dd-MMMM-yyyyHH:mm:ss”); //”21-July-2016 19:23:15″

Section11.10:SplittingaStringbyanotherstring

stringstr=”this–is–a–complete–sentence”;

string[]tokens=str.Split(new[]{“–“},StringSplitOptions.None);

Result:

[“this”,”is”,”a”,”complete”,”sentence”]

Section11.11:SplittingaStringbyspecificcharacter

stringhelloWorld=”helloworld,howisitgoing?”;

string[]parts1=helloWorld.Split(‘,’);

//parts1:[“helloworld”,”howisitgoing?”]

string[]parts2=helloWorld.Split(”);

//parts2:[“hello”, “world,” ,”how”,” is”, “it”, “going?”]

Section11.12:GettingSubstringsofagivenstring

stringhelloWorld=”HelloWorld!”;

stringworld=helloWorld.Substring(6);//world=”World!”

stringhello=helloWorld.Substring(0,5);//hello=”Hello”

Substringreturnsthestringupfromagivenindex,orbetweentwoindexes(bothinclusive).

Section 11.13: Determine whether a string begins with a given sequence

stringHelloWorld=”HelloWorld”;

HelloWorld.StartsWith(“Hello”);//true

HelloWorld.StartsWith(“Foo”);//false

Findingastringwithinastring

UsingtheSystem.String.Containsyoucanfindoutifaparticularstringexistswithinastring.Themethodreturns aboolean,trueifthestringexistselsefalse.

strings=”HelloWorld”;

boolstringExists=s.Contains(“ello”);                         //stringExists=trueasthestringcontainsthesubstring

Section 11.14: Getting a char at specific index and enumeratingthestring

You can use the Substringmethod to get any number of characters from a string at any given location. However, if youonlywantasinglecharacter,youcanusethestringindexertogetasinglecharacteratanygivenindexlike you

dowithanarray:

strings=”hello”;

charc=s[1];//Returns‘e’

Notice that the return type is char, unlike the Substringmethod which returns a stringtype. Youcanalsousetheindexertoiteratethroughthecharactersofthestring:

strings=”hello”;

foreach(charcins)

Console.WriteLine(c);

/*********Thiswillprinteachcharacteronanewline: h

e

l

l

o

**********/

Section11.15:Joininganarrayofstringsintoanewone

varparts=new[]{“Foo”,”Bar”,”Fizz”,”Buzz”};

varjoined=string.Join(“,”,parts);

//joined=”Foo,Bar,Fizz,Buzz”

Section11.16:Replacingastringwithinastring

UsingtheSystem.String.Replacemethod,youcanreplacepartofastringwithanotherstring.

strings=”HelloWorld”;

s=s.Replace(“World”,”Universe”);//s=”HelloUniverse”

Alltheoccurrencesofthesearchstringarereplaced.

Thismethodcanalsobeusedtoremovepartofastring,usingtheString.Emptyfield:

strings=”HelloWorld”;

s=s.Replace(“ell”,String.Empty);//s=”HoWorld”

Section11.17:ChangingthecaseofcharacterswithinaString

TheSystem.Stringclasssupportsanumberofmethodstoconvertbetweenuppercaseandlowercasecharacters in a string.

  • System.String.ToLowerInvariantisusedtoreturnaStringobjectconvertedtolowercase.
  • System.String.ToUpperInvariantisusedtoreturnaStringobjectconvertedtouppercase.

Note:Thereasontousetheinvariantversionsofthesemethodsistopreventproducingunexpectedculture- specific letters. This is explained here in detail.

Example:

strings=”MyString”;

s=s.ToLowerInvariant();//”mystring”

s=s.ToUpperInvariant();//”MYSTRING”

NotethatyoucanchoosetospecifyaspecificCulturewhenconvertingtolowercaseanduppercasebyusingthe String.ToLower(CultureInfo)and String.ToUpper(CultureInfo)methods accordingly.

Section 11.18: Concatenate an array of strings into a single string

TheSystem.String.Joinmethodallowstoconcatenateallelementsinastringarray,usingaspecifiedseparator between each element:

string[]words={“One”,”Two”,”Three”,”Four”};

stringsingleString=String.Join(“,”,words);//singleString=”One,Two,Three,Four”

Section11.19:StringConcatenation

StringConcatenationcanbedonebyusingtheSystem.String.Concatmethod,or(mucheasier)usingthe+

operator:

stringfirst=”Hello”;

stringsecond=”World”;

stringconcat=first+second;//concat=”HelloWorld”

concat=String.Concat(first,second);//concat=“HelloWorld”

InC#6thiscanbedoneasfollows:

stringconcat=$”{first},{second}”;

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments