Strings
Telerik Academy Alpha
Table of contents
What are strings?
What are strings?
-
string is a data type
-
System.String class
-
-
Sequence of characters (Unicode symbols)
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
H | e | l | l | o |
0x12345 | 0x12346 | 0x12347 | 0x12348 | 0x12349 |
Index |
---|
Variable |
Address |
string text = "Hello";
What are strings?
-
In the namespace System there is a class String which represents the string in C#
-
Strings use Unicode to support multiple languages and alphabets
-
Immutable
-
String objects are immutable: they cannot be changed after they have been created.
-
All the methods and operators actually return new object
string text = "Hello, Telerik Academy";
Console.WriteLine(text[0]);
// Compilation error indexer 'string.this[int]'
// cannot be assigned to -- it is read only
text[0] = 'A';
Immutable
string text = "Hello";
// This is a completely new object
text += ", Telerik Academy!";
Console.WriteLine(text); // Hello, Telerik Academy!
Immutable - Demo
Strings are arrays?
-
String objects have similarities to arrays but they are NOT arrays
-
It is like array of characters
-
Fixed Length ( str.Length)
-
Indexers ( str[0], str[1], ... str[str.Length-1] )
-
You can iterate them with for and foreach loops
-
String operations
Compare
Compare
string text = "Telerik Academy";
string text1 = "telerik academy";
Console.WriteLine(text == text1); // False
-
Equality compare with == operator
-
case-sensitive comparison
-
string text = "Telerik Academy";
string text1 = "Telerik Academy";
Console.WriteLine(text == text1); // True
Compare
-
Equality compare with Equals() method
-
the same as == in C# (ex: in Java this is not true)
-
you can control if it is case-sensitive/insensitive
-
with the second parameter StringComparison enum
-
-
string a = "Telerik Academy";
string a1 = "telerik academy";
// False
Console.WriteLine(a.Equals(a1));
// True
Console.WriteLine(a.Equals(a1, StringComparison.CurrentCultureIgnoreCase));
Concatenate
Concatenate
-
Concatenation of strings could be done with +/+= operators
string text = "Telerik Academy";
string text1 = "Alpha";
string newText = text + " " + text1;
Concatenate
-
Or with Concat() method
string text = "Telerik Academy";
string text1 = "Alpha";
string space = " ";
string newText = string.Concat(text, space, text1, space, "Rocks!");
// Telerik Academy Alpha Rocks!
Search in strings
Search
-
When you need to find a character in a string
-
IndexOf() method
-
returns the position of the element
-
or negative number if not found
-
case-sensitive but could be changed
-
-
string text = "Telerik Academy";
Console.WriteLine(text.IndexOf('T')); // 0
Console.WriteLine(text.IndexOf('t')); // -1
Search
-
IndexOf() has many useful overloads
-
with different parameters
-
startIndex, count comparisonType, etc.
-
-
string text = "Telerik Academy";
text.IndexOf('t'); // -1
text.IndexOf("te", StringComparison.CurrentCultureIgnoreCase); // 0
Search
-
In addition to IndexOf() there are other useful methods for searching
-
LastIndexOf()
-
IndexOfAny()
-
LastIndexOfAny()
-
string text = "Telerik Academy";
Console.WriteLine(text.IndexOf('e')); // 1
Console.WriteLine(text.LastIndexOf('e')); // 12
Extract parts
Extract
-
You can get part of the string with optional start and end position
string text = "Telerik Academy";
Console.WriteLine(text.Substring(8)); // Academy
Console.WriteLine(text.Substring(0, 7)); // Telerik
Extract delimited
-
You can all the parts of the string as array by delimiter (",", ".", " " or any symbol you need)
string text = "Telerik Academy";
string[] arr = text.Split(' ');
Console.WriteLine(arr.Length); // 2
Extract delimited
-
There could be empty string when splitting
string text = "Telerik Academy ";
// ["Telerik", "Academy", ""] empty string at the end
string[] arr = text.Split(' ');
Console.WriteLine(arr.Length); // 3
Extract delimited
-
How to handle empty strings (StringSplitOptions.RemoveEmptyEntries)
string text = "Telerik Academy ";
// you should pass array of chars or strings
var splitSymbols = new char[] { ' ', ',' };
// ["Telerik", "Academy"]
string[] arr = text.Split(splitSymbols, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(arr.Length); // 2
Replace and remove
Replace
-
You can replace all occurrences of a char/string in another string with new value
-
Replace() method
-
string text = "Telerik Academy";
// Replace returns new string (strings are immutable)
var newString = text.Replace("Telerik", "Alpha");
Console.WriteLine(newString); // Alpha Academy
Remove/Delete
-
You can remove part of a string
-
Remove() method
-
startIndex
-
count (optional)
-
-
string text = "Telerik Academy";
// Remove returns new string (strings are immutable)
var newString = text.Remove(0, 8);
Console.WriteLine(newString); // Academy
Casing, trimming
Casing
-
You can change character casing
-
ToUpper()
-
ToLower()
-
etc.
-
string text = "Telerik Academy";
// ToUpper returns new string (strings are immutable)
var newString = text.ToUpper();
Console.WriteLine(newString); // TELERIK ACADEMY
Trim
-
You can trim the string (any character) from start/end
-
Trim() - trims start and end from whitespace
-
TrimEnd() - only the end
-
TrimStart() - only the start
-
all the methods could contain different symbols to trim
-
-
string text = " Telerik Academy!";
// The methods could be chained
var newString = text.Trim().TrimEnd('!');
Console.WriteLine(newString);
Demo
StringBuilder
Mutate the string
StringBuilder
-
Performing multiple concatenations (ex: in for loop) is a slow operation due to the immutability if the strings
-
Every time you add a string to an existing one, there is a new object created and all the previous values are copied in it
-
It is slow if you want to add multiple times or build a long string
-
If you just make a single concatenation it is okay to use simple string concatenation
-
-
StringBuilder
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append("Telerik");
sBuilder.Append(" Academy");
T | e | l | e | r | i | k | A | c |
---|
a | d | e | m | y |
---|
StringBuilder
-
StringBuilder uses internal array and this makes it faster
-
In the new versions of .NET (>= 4.0) StringBuilder uses Linked List of StringBuilder instances
-
Adding is much faster
-
-
If you need to add many strings or build a large string (ex: in a for loop) you must use StringBuilder
StringBuilder
int count = 10000;
string str = string.Empty;
StringBuilder strBuilder = new StringBuilder();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
str += i;
}
Console.WriteLine($"String concatenate: {sw.ElapsedMilliseconds}"); // ~ 12500 ms
sw.Start();
for (int i = 0; i < count; i++)
{
strBuilder.Append(i);
}
Console.WriteLine($"StringBuilder append: {sw.ElapsedMilliseconds}"); // ~ 10 ms
Summary
String summary
-
Strings are immutable
-
Cannot be rewritten
-
-
All the operations over strings return new string (object)
-
Therefore they are relatively slow
-
-
All the objects in C# have ToString() method
-
If you need to add many chars/strings and make multiple such operations
-
Consider using StringBuilder
-
Resources
Questions?
[C#] Strings
By telerikacademy
[C#] Strings
- 1,224