当前位置: 首页>>代码示例>>C#>>正文


C# String类代码示例

本文整理汇总了C#中System.String的典型用法代码示例。如果您正苦于以下问题:C# String类的具体用法?C# String怎么用?C# String使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


String类属于System命名空间,在下文中一共展示了String类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1:

string string1 = "This is a string created by assignment.";
Console.WriteLine(string1);
string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
Console.WriteLine(string2a);
string string2b = @"The path is C:\PublicDocuments\Report1.doc";
Console.WriteLine(string2b);
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String

输出:

This is a string created by assignment.
The path is C:\PublicDocuments\Report1.doc
The path is C:\PublicDocuments\Report1.doc

示例2: string

char[] chars = { 'w', 'o', 'r', 'd' };
sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };

// Create a string from a character array.
string string1 = new string(chars);
Console.WriteLine(string1);

// Create a string that consists of a character repeated 20 times.
string string2 = new string('c', 20);
Console.WriteLine(string2);

string stringFromBytes = null;
string stringFromChars = null;
unsafe
{
   fixed (sbyte* pbytes = bytes)
   {
      // Create a string from a pointer to a signed byte array.
      stringFromBytes = new string(pbytes);
   }
   fixed (char* pchars = chars)
   {
      // Create a string from a pointer to a character array.
      stringFromChars = new string(pchars);
   }
}
Console.WriteLine(stringFromBytes);
Console.WriteLine(stringFromChars);
开发者ID:.NET开发者,项目名称:System,代码行数:28,代码来源:String

输出:

word
cccccccccccccccccccc
ABCDE
word

示例3:

string string1 = "Today is " + DateTime.Now.ToString("D") + ".";
Console.WriteLine(string1);

string string2 = "This is one sentence. " + "This is a second. ";
string2 += "This is a third sentence.";
Console.WriteLine(string2);
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String

输出:

Today is Tuesday, July 06, 2011.
This is one sentence. This is a second. This is a third sentence.

示例4:

string sentence = "This sentence has five words.";
// Extract the second word.
int startPosition = sentence.IndexOf(" ") + 1;
string word2 = sentence.Substring(startPosition,
                                  sentence.IndexOf(" ", startPosition) - startPosition);
Console.WriteLine("Second word: " + word2);
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String

输出:

Second word: sentence

示例5: DateTime

DateTime dateAndTime = new DateTime(2011, 7, 6, 7, 32, 0);
double temperature = 68.3;
string result = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                              dateAndTime, temperature);
Console.WriteLine(result);
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:String

输出:

At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.

示例6: Main

//引入命名空间
using System;
using System.Globalization;
using System.IO;

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\graphemes.txt");
      string grapheme = "\u0061\u0308";
      sw.WriteLine(grapheme);
      
      string singleChar = "\u00e4";
      sw.WriteLine(singleChar);
            
      sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                   String.Equals(grapheme, singleChar, 
                                 StringComparison.CurrentCulture));
      sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, 
                   String.Equals(grapheme, singleChar, 
                                 StringComparison.Ordinal));
      sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, 
                   String.Equals(grapheme.Normalize(), 
                                 singleChar.Normalize(), 
                                 StringComparison.Ordinal));
      sw.Close(); 
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:29,代码来源:String

输出:

ä
ä
ä = ä (Culture-sensitive): True
ä = ä (Ordinal): False
ä = ä (Normalized Ordinal): True

示例7:

string surrogate = "\uD800\uDC03";
for (int ctr = 0; ctr < surrogate.Length; ctr++) 
   Console.Write("U+{0:X2} ", Convert.ToUInt16(surrogate[ctr]));

Console.WriteLine();
Console.WriteLine("   Is Surrogate Pair: {0}", 
                  Char.IsSurrogatePair(surrogate[0], surrogate[1]));
开发者ID:.NET开发者,项目名称:System,代码行数:7,代码来源:String

输出:

U+D800 U+DC03
Is Surrogate Pair: True

示例8: if

string s1 = "This string consists of a single short sentence.";
int nWords = 0;

s1 = s1.Trim();      
for (int ctr = 0; ctr < s1.Length; ctr++) {
   if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr]))
      nWords++;              
}
Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                  s1, nWords);
开发者ID:.NET开发者,项目名称:System,代码行数:10,代码来源:String

输出:

The sentence
This string consists of a single short sentence.
has 8 words.

示例9: if

string s1 = "This string consists of a single short sentence.";
int nWords = 0;

s1 = s1.Trim();      
foreach (var ch in s1) {
   if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch))
      nWords++;              
}
Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                  s1, nWords);
开发者ID:.NET开发者,项目名称:System,代码行数:10,代码来源:String

输出:

The sentence
This string consists of a single short sentence.
has 8 words.

示例10: foreach

// First sentence of The Mystery of the Yellow Room, by Leroux.
string opening = "Ce n'est pas sans une certaine émotion que "+
                 "je commence à raconter ici les aventures " +
                 "extraordinaires de Joseph Rouletabille."; 
// Character counters.
int nChars = 0;
// Objects to store word count.
List<int> chars = new List<int>();
List<int> elements = new List<int>();

foreach (var ch in opening) {
   // Skip the ' character.
   if (ch == '\u0027') continue;
        
   if (Char.IsWhiteSpace(ch) | (Char.IsPunctuation(ch))) {
      chars.Add(nChars);
      nChars = 0;
   }
   else {
      nChars++;
   }
}

System.Globalization.TextElementEnumerator te = 
   System.Globalization.StringInfo.GetTextElementEnumerator(opening);
while (te.MoveNext()) {
   string s = te.GetTextElement();   
   // Skip the ' character.
   if (s == "\u0027") continue;
   if ( String.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && Char.IsPunctuation(Convert.ToChar(s)))) {
      elements.Add(nChars);         
      nChars = 0;
   }
   else {
      nChars++;
   }
}

// Display character counts.
Console.WriteLine("{0,6} {1,20} {2,20}",
                  "Word #", "Char Objects", "Characters"); 
for (int ctr = 0; ctr < chars.Count; ctr++) 
   Console.WriteLine("{0,6} {1,20} {2,20}",
                     ctr, chars[ctr], elements[ctr]);
开发者ID:.NET开发者,项目名称:System,代码行数:44,代码来源:String

输出:

Word #         Char Objects           Characters
0                    2                    2
1                    4                    4
2                    3                    3
3                    4                    4
4                    3                    3
5                    8                    8
6                    8                    7
7                    3                    3
8                    2                    2
9                    8                    8
10                    2                    1
11                    8                    8
12                    3                    3
13                    3                    3
14                    9                    9
15                   15                   15
16                    2                    2
17                    6                    6
18                   12                   12

示例11: ToString

public string ToString(string format, IFormatProvider provider) 
{
   if (String.IsNullOrEmpty(format)) format = "G";  
   if (provider == null) provider = CultureInfo.CurrentCulture;
   
   switch (format.ToUpperInvariant())
   {
      // Return degrees in Celsius.    
      case "G":
      case "C":
         return temp.ToString("F2", provider) + "°C";
      // Return degrees in Fahrenheit.
      case "F": 
         return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F";
      // Return degrees in Kelvin.
      case "K":   
         return (temp + 273.15).ToString();
      default:
         throw new FormatException(
               String.Format("The {0} format string is not supported.", 
                             format));
   }                                   
}
开发者ID:.NET开发者,项目名称:System,代码行数:23,代码来源:String

示例12: Main

//引入命名空间
using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      
      string str = String.Empty;
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                           false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         str += Convert.ToChar(rnd.Next(1, 0x0530)); 
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:24,代码来源:String

示例13: Main

//引入命名空间
using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      StringBuilder sb = new StringBuilder();
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                                         false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         sb.Append(Convert.ToChar(rnd.Next(1, 0x0530))); 
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:23,代码来源:String

示例14: Main

//引入命名空间
using System;
using System.Globalization;
using System.Threading;

public class Example
{
   const string disallowed = "file";
   
   public static void Main()
   {
      IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
   }

   private static void IsAccessAllowed(String resource)
   {
      CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
                                 CultureInfo.CreateSpecificCulture("tr-TR") };
      String scheme = null;
      int index = resource.IndexOfAny( new Char[] { '\\', '/' } );
      if (index > 0) 
         scheme = resource.Substring(0, index - 1);

      // Change the current culture and perform the comparison.
      foreach (var culture in cultures) {
         Thread.CurrentThread.CurrentCulture = culture;
         Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
         Console.WriteLine(resource);
         Console.WriteLine("Access allowed: {0}", 
                           ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase));      
         Console.WriteLine();
      }   
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:34,代码来源:String

输出:

Culture: English (United States)
FILE:\\\c:\users\user001\documents\FinancialInfo.txt
Access allowed: False

Culture: Turkish (Turkey)
FILE:\\\c:\users\user001\documents\FinancialInfo.txt
Access allowed: True

示例15: Main

//引入命名空间
using System;
using System.Globalization;
using System.IO;

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\case.txt");   
      string[] words = { "file", "sıfır", "Dženana" };
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"),  
                                 new CultureInfo("tr-TR") };

      foreach (var word in words) {
         sw.WriteLine("{0}:", word);
         foreach (var culture in cultures) {
            string name = String.IsNullOrEmpty(culture.Name) ? 
                                 "Invariant" : culture.Name;
            string upperWord = word.ToUpper(culture);
            sw.WriteLine("   {0,10}: {1,7} {2, 38}", name, 
                         upperWord, ShowHexValue(upperWord));
         }
         sw.WriteLine();  
      }
      sw.Close();
   }

   private static string ShowHexValue(string s)
   {
      string retval = null;
      foreach (var ch in s) {
         byte[] bytes = BitConverter.GetBytes(ch);
         retval += String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0]);     
      }
      return retval;
   } 
}
开发者ID:.NET开发者,项目名称:System,代码行数:39,代码来源:String

输出:

file:
Invariant:    FILE               00 46 00 49 00 4C 00 45 
en-US:    FILE               00 46 00 49 00 4C 00 45 
tr-TR:    FİLE               00 46 01 30 00 4C 00 45 

sıfır:
Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52 
en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52 
tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52 

Dženana:
Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41 
en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41


注:本文中的System.String类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。