string
In this chapter you will learn:
- What is string type
- String are immutable
- Empty string
- Get string length and output string
- String equality
Get to know string type
A string is a set of characters enclosed by double quotes. For example, "this is a test" is a string.
To store an immutable sequence of unicode char, we can use
string
(System.String) type.
C# uses double quote to wrap string
literals.
using System;//j a v a 2 s .c om
class Program
{
static void Main(string[] args)
{
string str = "demo from java2s.com";
Console.WriteLine(str);
}
}
The output:
String are immutable
using System;/*j ava2 s . c o m*/
using System.Text;
class Program
{
static void Main(string[] args)
{
// Set initial string value.
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);
// Uppercase the s1?
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);
// Nope! s1 is in the same format!
Console.WriteLine("s1 = {0}", s1);
string s2 = "My other string";
s2 = "New string value";
}
}
Empty string
using System;//from ja v a2 s . c o m
public class MainClass
{
public static void Main(string[] args)
{
string address = String.Empty;
}
}
Get string length and output string
using System; //from j a v a2s .co m
class MainClass {
public static void Main() {
string str1 = "ABCDEabcde1234567890";
Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " + str1.Length);
}
}
The code above generates the following result.
String equality
string
is a reference type.
However C# uses the ==
to
check the equality between two strings.
using System;//from ja va 2 s .c o m
class Program
{
static void Main(string[] args)
{
string s1 = "java2s.com";
string s2 = "Java2s.com";
Console.WriteLine(s1.ToUpper() == s2.ToUpper());
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » String