String copy

In this chapter you will learn:

  1. Use the Copy() method to copy a string
  2. Check the equality for copied strings
  3. Copy sub string

Copy a string

using System;/*j  a  v a  2s .c  o  m*/

class MainClass
{

  public static void Main()
  {
    
    string myString4 = "string4";
    Console.WriteLine( myString4);
    string myString7 = String.Copy(myString4);
    Console.WriteLine(myString7);
  }

}

Check the equality for copied strings

using System;  /*from   j a v a  2s  .c o  m*/
  
class MainClass {   
  public static void Main() {   
    string str1 = "ABCDEabcde1234567890";   
    string str2 = string.Copy(str1);  
    string str3 = "asdf";   
  
   
    // compare strings 
    if(str1 == str2)   
      Console.WriteLine("str1 == str2");   
    else   
      Console.WriteLine("str1 != str2");   
   
    if(str1 == str3)   
      Console.WriteLine("str1 == str3");   
    else   
      Console.WriteLine("str1 != str3");   
  
  }

}

The code above generates the following result.

Copy sub string

using System;// j  a v a 2s.c  om

class Class1
{
  [STAThread]
  static void Main(string[] args)
  {
      string source = "ABCD";
      char [] dest = { '1', '2', '3', '4', '5', '6', '7', '8' };

      Console.Write( "Char array before = " );
      Console.WriteLine( dest );

      // copy substring into char array
      source.CopyTo( 0, dest, 4, source.Length );

      Console.Write( "Char array after = " );
      Console.WriteLine( dest );

      // copy back into source string
      source = new String( dest );

      Console.WriteLine( "New source = {0}\n", source );

  }
}

Next chapter...

What you will learn in the next chapter:

  1. Use the Join() method to join strings
  2. Join string by |
Home » C# Tutorial » String
string
String creation
Char in string
Compare strings
String equality
String concatanation
String copy
String Join
String split
String Search for Index
String contains
String start with
String insert
String case
Replacing substring
Remove from a string
Substring
Escape Characters
String verbatim
String padding
Switch on String
String trim
String intern
String normalization
Empty String