Csharp/CSharp Tutorial/String/String — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:16, 26 мая 2010

Basic String functionality

using System;
using System.Collections.Generic;
using System.Text;

  class Program
  {
    static void Main(string[] args)
    {
      string firstName = "Buddy";
      Console.WriteLine("Value of firstName: {0}", firstName);
      Console.WriteLine("firstName has {0} characters.", firstName.Length);
      Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
      Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
      Console.WriteLine("firstName contains the letter y?: {0}", firstName.Contains("y"));
      Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
    }
  }

Declaration of string

  1. strings are objects.
  2. string is a reference type.
  1. static string Copy(string str)
  2. int CompareTo(string str)
  3. int IndexOf(string str)
  4. int LastIndexOf(string str)
  5. string ToLower( )
  6. string ToUpper( )

A string is a set of characters enclosed by double quotes. For example,


"this is a test"

Display all the characters in myString using a for loop

using System;
class MainClass
{
  public static void Main()
  {
    string myString = "To be or not to be";
    
    for (int count = 0; count < myString.Length; count++)
    {
      Console.WriteLine("myString[" + count + "] = " + myString[count]);
    }
  }
}
myString[0] = T
myString[1] = o
myString[2] =
myString[3] = b
myString[4] = e
myString[5] =
myString[6] = o
myString[7] = r
myString[8] =
myString[9] = n
myString[10] = o
myString[11] = t
myString[12] =
myString[13] = t
myString[14] = o
myString[15] =
myString[16] = b
myString[17] = e

Empty string

using System;
using System.IO;
using System.Text;
public class MainClass
{
    public static void Main(string[] args)
    {
        string address = String.Empty;
    }
}

Error; string Is Immutable

class Uppercase
{
  static void Main()
  {
      string text;
      System.Console.Write("Enter text: ");
      text = System.Console.ReadLine();
      text.ToUpper();
      System.Console.WriteLine(text);
  }
}

String are immutable

using System;
using System.Collections.Generic;
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";
    }
  }

String is object

using System;
class MainClass
{
    static void Main(string[] args) {
        string strOriginal = "Original String";
        Console.WriteLine( "Value of strOriginal before call: {0}", strOriginal );
        TryToAlterString( strOriginal );
        Console.WriteLine( "Value of strOriginal after call: {0}", strOriginal );
    }
    static void TryToAlterString(string str) {
        str = "Modified String";
    }
}
Value of strOriginal before call: Original String
Value of strOriginal after call: Original String

Use Indexer to reference chars in a string

using System;
class MainClass
{
  public static void Main()
  {
    string myString = "To be or not to be";
    
    for (int count = 0; count < myString.Length; count++)
    {
      Console.WriteLine("myString[" + count + "] = " + myString[count]);
    }
  }
}
myString[0] = T
myString[1] = o
myString[2] =
myString[3] = b
myString[4] = e
myString[5] =
myString[6] = o
myString[7] = r
myString[8] =
myString[9] = n
myString[10] = o
myString[11] = t
myString[12] =
myString[13] = t
myString[14] = o
myString[15] =
myString[16] = b
myString[17] = e

Use the addition operator (+) to concatenate strings

using System;
class MainClass
{
  public static void Main()
  {
    string myString6 = "To be, " + "or not to be";
    Console.WriteLine("\"To be, \" + \"or not to be\" = " + myString6);
  }
}
"To be, " + "or not to be" = To be, or not to be

Use the Compare() method to compare strings

using System;
class MainClass
{
  public static void Main()
  {
    
    int result;
    result = String.rupare("bbc", "abc");
    Console.WriteLine("String.rupare(\"bbc\", \"abc\") = " + result);
    result = String.rupare("abc", "bbc");
    Console.WriteLine("String.rupare(\"abc\", \"bbc\") = " + result);
    result = String.rupare("bbc", "bbc");
    Console.WriteLine("String.rupare(\"bbc\", \"bbc\") = " + result);
    result = String.rupare("bbc", "BBC", true);
    Console.WriteLine("String.rupare(\"bbc\", \"BBC\", true) = " + result);
    result = String.rupare("bbc", "BBC", false);
    Console.WriteLine("String.rupare(\"bbc\", \"BBC\", false) = " + result);
    result = String.rupare("Hello World", 6, "Goodbye World", 8, 5);
    Console.WriteLine("String.rupare(\"Hello World\", 6, " + "\"Goodbye World\", 8, 5) = " + result);
  }
}
String.rupare("bbc", "abc") = 1
String.rupare("abc", "bbc") = -1
String.rupare("bbc", "bbc") = 0
String.rupare("bbc", "BBC", true) = 0
String.rupare("bbc", "BBC", false) = -1
String.rupare("Hello World", 6, "Goodbye World", 8, 5) = 0

Use the Concat() method to concatenate strings

using System;
class MainClass
{
  public static void Main()
  {
    string myString4 = String.Concat("A, ", "B");
    Console.WriteLine("String.Concat(\"A, \", \"B\") = "+ myString4);
    string myString5 = String.Concat("A, ", "B, ", "and countrymen");
    Console.WriteLine("String.Concat(\"A, \", \"B, \", " + "\"and countrymen\") = " + myString5);
  }
}
String.Concat("A, ", "B") = A, B
String.Concat("A, ", "B, ", "and countrymen") = A, B, and countrymen

Use the Copy() method to copy a string

using System;
class MainClass
{
  public static void Main()
  {
    
    string myString4 = "string4";
    Console.WriteLine("myString4 = " + myString4);
    Console.WriteLine("Copying myString4 to myString7 using Copy()");
    string myString7 = String.Copy(myString4);
    Console.WriteLine("myString7 = " + myString7);
  }
}
myString4 = string4
Copying myString4 to myString7 using Copy()
myString7 = string4

Use the Equals() method and equality operator to check if two strings are equal

using System;
class MainClass
{
  public static void Main()
  {
    bool boolResult;
    string myString = "str";
    string myString2 = "str2";
    
    boolResult = String.Equals("bbc", "bbc");
    Console.WriteLine("String.Equals(\"bbc\", \"bbc\") is " + boolResult);
    
    boolResult = myString.Equals(myString2);
    Console.WriteLine("myString.Equals(myString2) is " + boolResult);
    
    boolResult = myString == myString2;
    Console.WriteLine("myString == myString2 is " + boolResult);
  }
}
String.Equals("bbc", "bbc") is True
myString.Equals(myString2) is False
myString == myString2 is False

Use the Format() method to format a string

using System;
class MainClass
{
  public static void Main()
  {
    
    float myFloat = 1234.56789f;
    string myString8 = String.Format("{0, 10:f3}", myFloat);
    Console.WriteLine("String.Format(\"{0, 10:f3}\", myFloat) = " + myString8);
  }
}
String.Format("{0, 10:f3}", myFloat) =   1234.568

Use the IndexOfAny() and LastIndexOfAny() methods to search for character arrays in a string

using System;
class MainClass
{
  public static void Main()
  {
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString = String.Join(".", myStrings);   
    
    char[] myChars = {"b", "e"};
    int index = myString.IndexOfAny(myChars);
    Console.WriteLine(""b" and "e" occur at index " + index + " of myString");
    index = myString.LastIndexOfAny(myChars);
    Console.WriteLine(""b" and "e" last occur at index " + index + " of myString");
  }
}
"b" and "e" occur at index 3 of myString
"b" and "e" last occur at index 17 of myString

Use the Insert(), Remove(), and Replace() methods to modify strings

using System;
class MainClass
{
  public static void Main()
  {
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString = String.Join(".", myStrings);   
    
    string myString10 = myString.Insert(6, "A, ");
    Console.WriteLine("myString.Insert(6, \"A, \") = " + myString10);
    string myString11 = myString10.Remove(14, 7);
    Console.WriteLine("myString10.Remove(14, 7) = " + myString11);
    string myString12 = myString11.Replace(",", "?");
    Console.WriteLine("myString11.Replace(",", "?") = " + myString12);
    string myString13 = myString12.Replace("to be", "Or not to be A");
    Console.WriteLine("myString12.Replace(\"to be\", \"Or not to be A\") = " + myString13);
  }
}
myString.Insert(6, "A, ") = To.be.A, or.not.to.be
myString10.Remove(14, 7) = To.be.A, or.no
myString11.Replace(",", "?") = To.be.A? or.no
myString12.Replace("to be", "Or not to be A") = To.be.A? or.no

Use the Join() method to join strings

using System;
class MainClass
{
  public static void Main()
  {
    
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString9 = String.Join(".", myStrings);
    Console.WriteLine("myString9 = " + myString9);
  }
}
myString9 = To.be.or.not.to.be

Use the PadLeft() and PadRight() methods to align strings

using System;
class MainClass
{
  public static void Main()
  {
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString = String.Join(".", myStrings);   
    
    string myString14 = "(" + myString.PadLeft(20) + ")";
    Console.WriteLine(""(" + myString.PadLeft(20) + ")" = " + myString14);
    string myString15 = "(" + myString.PadLeft(20, ".") + ")";
    Console.WriteLine(""(" + myString.PadLeft(20, ".") = " + myString15);
    string myString16 = "(" + myString.PadRight(20) + ")";
    Console.WriteLine(""(" + myString.PadRight(20) + ")" = " + myString16);
    string myString17 = "(" + myString.PadRight(20, ".") + ")";
    Console.WriteLine(""(" + myString.PadRight(20, ".") + ")" = " + myString17);
  }
}
"(" + myString.PadLeft(20) + ")" = (  To.be.or.not.to.be)
"(" + myString.PadLeft(20, ".") = (..To.be.or.not.to.be)
"(" + myString.PadRight(20) + ")" = (To.be.or.not.to.be  )
"(" + myString.PadRight(20, ".") + ")" = (To.be.or.not.to.be..)

Use the Split() method to split strings

using System;
class MainClass
{
  public static void Main()
  {
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString9 = String.Join(".", myStrings);    
    myStrings = myString9.Split(".");
    foreach (string mySplitString in myStrings)
    {
      Console.WriteLine("mySplitString = " + mySplitString);
    }
  }
}
mySplitString = To
mySplitString = be
mySplitString = or
mySplitString = not
mySplitString = to
mySplitString = be

Use the Substring() method to retrieve substrings

using System;
class MainClass
{
  public static void Main()
  {
    
    string[] myStrings = {"To", "be", "or", "not", "to", "be"};
    string myString = String.Join(".", myStrings);   
    
    
    string myString21 = myString.Substring(3);
    Console.WriteLine("myString.Substring(3) = " + myString21);
    string myString22 = myString.Substring(3, 2);
    Console.WriteLine("myString.Substring(3, 2) = " + myString22);
  }
}
myString.Substring(3) = be.or.not.to.be
myString.Substring(3, 2) = be

Use the Trim(), TrimStart(), and TrimEnd() methods to trim strings

using System;
class MainClass
{
  public static void Main()
  {
    
    string myString18 = "(" + "  Whitespace  ".Trim() + ")";
    Console.WriteLine(""(" + \"  Whitespace  \".Trim() + ")" = " + myString18);
    string myString19 = "(" + "  Whitespace  ".TrimStart() + ")";
    Console.WriteLine(""(" + \"  Whitespace  \".TrimStart() + ")" = " + myString19);
    string myString20 = "(" + "  Whitespace  ".TrimEnd() + ")";
    Console.WriteLine(""(" + \"  Whitespace  \".TrimEnd() + ")" = " + myString20);
  }
}
"(" + "  Whitespace  ".Trim() + ")" = (Whitespace)
"(" + "  Whitespace  ".TrimStart() + ")" = (Whitespace  )
"(" + "  Whitespace  ".TrimEnd() + ")" = (  Whitespace)

Working with Strings

class Uppercase
{
  static void Main()
  {
      System.Console.Write("Enter text: ");
      var text = System.Console.ReadLine();
      var uppercase = text.ToUpper();
      System.Console.WriteLine(uppercase);
  }
}