Home  >  Article  >  Backend Development  >  String literals vs. string objects in C#

String literals vs. string objects in C#

WBOY
WBOYforward
2023-09-06 17:45:07931browse

C# 中的字符串文字与字符串对象

String literals

String literals or constants are enclosed in double quotes "" or @"". Strings contain characters similar to character literals: plain characters, escape sequences, and universal characters.

The following are some examples of string literals -

Hello, World"
"Welcome, \

The following are examples showing the usage of string literals -

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         // string
         string str1 ="Hello, World";
         Console.WriteLine(str1);

         // Multi-line string
         string str2 = @"Welcome,
         Hope you are doing great!";

         Console.WriteLine(str2);
      }
   }
}

String Object

Create a string object using one of the following methods -

  • By assigning a string literal to a string variable
  • By using the String class constructor
  • By using the string concatenation operator ( )
  • By retrieving a property or calling a method that returns a string
  • Convert a value or object to its string representation by calling a formatting method

Here's how to create a string object and compare two strings -

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         string str1 = "John";
         string str2 = "Andy";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}

The above is the detailed content of String literals vs. string objects in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete