Chapter14:StringManipulation

No Comments

Section14.1:Replacingastringwithinastring

UsingtheSystem.String.Replacemethod,youcanreplacepartofastringwithanotherstring.

strings=”HelloWorld”;

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

Alltheoccurrencesofthesearchstringarereplaced:

strings=”HelloWorld”;

s=s.Replace(“l”,”L”);//s=”HeLLoWorLD”

String.Replacecanalsobeusedtoremovepartofastring,byspecifyinganemptystringasthereplacementvalue:

strings=”HelloWorld”;

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

Section14.2:Findingastringwithinastring

UsingtheSystem.String.Containsyoucanfindoutifaparticularstringexistswithinastring.Themethodreturns aboolean,trueifthestringexistselsefalse.

strings=”HelloWorld”;

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

UsingtheSystem.String.IndexOfmethod,youcanlocatethestartingpositionofasubstringwithinanexisting string.

Notethereturnedpositioniszero-based,avalueof-1isreturnedifthesubstringisnotfound.

strings=”HelloWorld”;

intlocation=s.IndexOf(“ello”);//location=1

Tofindthefirstlocationfromtheendofastring,usetheSystem.String.LastIndexOfmethod:

strings=”HelloWorld”;

intlocation=s.LastIndexOf(“l”);//location=9

Section14.3:Removing(Trimming)white-spacefromastring

TheSystem.String.Trimmethodcanbeusedtoremoveallleadingandtrailingwhite-spacecharactersfroma string:

strings=” Stringwithspacesatbothends

s=s.Trim();//s=”Stringwithspacesatbothends”

Inaddition:

Toremovewhite-spaceonlyfromthebeginningofastringuse:System.String.TrimStart

  • Toremovewhite-spaceonlyfromtheendofastringuse:System.String.TrimEnd

Substringtoextractpartofastring.

TheSystem.String.Substringmethodcanbeusedtoextractaportionofthestring.

strings=”Aportionofwordthatisretained”;

s=str.Substring(26);            //s=”retained”

s1=s.Substring(0,5);                //s=”Apor”

Section14.4:Splittingastringusingadelimiter

Use the System.String.Splitmethod to return a string array that contains substrings of the original string, split basedonaspecifieddelimiter:

stringsentence=”OneTwoThreeFour”;

string[]stringArray=sentence.Split(”);

foreach(stringwordinstringArray)

{

Console.WriteLine(word);

}

Output:

One

Two

Three

Four

Section14.5:Concatenateanarrayofstringsintoasingle string

TheSystem.String.Joinmethodallowstoconcatenateallelementsinastringarray,usingaspecifiedseparator between each element:

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

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

Section14.6:StringConcatenation

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

operator:

stringfirst=”Hello”;

stringsecond=”World”;

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

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

Section14.7:Changingthecaseofcharacterswithina String

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.

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