Text and Strings - Part 1
Up to this point we've learned about primitive types that are mostly numeric and also the Boolean types of true and false. Let's move forward and get to a real type that everybody needs to use inside their applications, namely strings. Sharp strings are an array a collection of character types. This makes sense when you think about it as a string, a block of text, is just a collection of characters. This means a bunch of different things for us as we look at working with strings to manage and create text content that we want to display on screen whether it's in a Windows application, a website, or even a mobile app for your phone.
Download this lesson as a Polyglot Notebook to open in Visual Studio Code, or open directly in your web browser with Binder.
Strings are in extensive and interesting topic in C# and .NET. This is the first of several parts in which we'll learn about strings, including a more advanced topic very much later in the course.
Let's start with the basics and we can declare a string by outlining it with the double quote character "
. If we wanted to declare our players names for a game of cards we could do it with the following syntax:
string playerOneName = "Jeff"; string playerTwoName = "Cris"; display(playerOneName)
Of course as we learned previously we can also use the var
keyword to declare variables as well. Let's rewrite that last declaration of our players names using the var keyword.
var playerOneName = "Jeff"; var playerTwoName = "Cris"; display(playerTwoName)
That's simple enough and builds on what we've previously learned. Folks when they work with strings want to combine them or grab parts of strings or look up where values exist inside of strings. Take a look at some of these operations to manage and analyze the content of text content.
Grabbing Part of a String
Since the string is just a collection of characters, we can grab individual characters by referencing them with a zero-based index and square brackets [ ]
We could define the standard suits in a deck of poker playing cards and grab the first initial of each suit using syntax like this:
var suit1 = "Clubs"; var suit2 = "Diamonds"; var suit3 = "Hearts"; var suit4 = "Spades"; var clubsInitial = suit1[0]; var diamondsInitial = suit2[0]; var heartsInitial = suit3[0]; var spadesInitial = suit4[0];
We can also use the Substring
method to isolate and return text from a given position and length inside of a string. Perhaps we want to grab just the first name of this player.
var playerOne = "Jeff Fritz"; var playerOneFirstName = playerOne.Substring(0,4); display(playerOneFirstName);
Substring
can also be used to grab from a point in the string through the end by omitting the second argument to the substring method.
var playerOneLastName = playerOne.Substring(5);
display(playerOneLastName);
Analyzing Strings
There are a number of methods and properties available that let you inspect a string. Let's start with the Length
property:
var playerOneCards = "3H4H"; display(playerOneCards.Length);
We can also search a string for the position of a character inside the string with the IndexOf
method:
var nextHand = "9H9D"; display(nextHand.IndexOf('D'));
What does IndexOf
return if it doesn't find the character in the string?
var thirdHand = "7H8H"; display(thirdHand.IndexOf('D'));
Modifying Strings
It's one thing to get a part of a string and work with it, but sometimes we just want to replace parts of the string or even to remove content from the string. Let's take a look at how we can replace content in strings with the Replace
method. In this sample, let's replace the space between the player's name with an underscore _
character:
var playerOne = "Jeff Fritz"; display(playerOne.Replace(' ', '_'));
We can also remove characters from within a string variable using the same arguments as we previously did with the Substring
method. The Remove
method removes the characters and returns the string:
var diamonds = "Diamonds"; display(diamonds.Remove(7)); display(diamonds.Remove(1)); display(diamonds.Remove(2,5));
Perhaps there are extra spaces or other characters that you'd like to clean up at the beginning or end of a string. You can use the Trim
, TrimStart
, and TrimEnd
methods to remove these extra characters:
var suits = "Clubs Diamonds Hearts Spades"; var clubs = suits.Substring(0,6); display(clubs); clubs = clubs.Trim(); // Use Trim with no arguments to remove spaces display(clubs); display(clubs.TrimEnd('s'));
Combining Strings
We've looked at analyzing and grabbing various parts of strings but what about combining strings? We started with a full name for a player but what if we have their individual first name and last name and want to combine names? Or maybe we have a collection of card strings that we want to combine together to represent a player's hand. We do that? Let's start with combining a players name using a simple +
operator
var firstName = "Jeff"; var lastName = "Fritz"; display(firstName + ' ' + lastName);
Notice that we can insert a character in the middle of the combination of these two strings. What if instead of inserting a space character, we inserted something else? What happens then?
Let's combine various cards into a larger 'Hand' variable. We can also use the Concat
method with the various strings we would like to combine:
var card1 = "2C"; var card2 = "2D"; var card3 = "2S"; var myHand = string.Concat(card1, card2, card3); display(myHand);
If we have to combine lots of strings, or an unknown number of strings, we can use a more efficient object called a StringBuilder
to combine those values. The StringBuilder
is used like this:
var myHand = new StringBuilder(); var card4 = "8C"; var card5 = "8D"; var card6 = "8S"; myHand.Append(card4); myHand.Append(card5); myHand.Append(card6); display(myHand.ToString());