• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# String类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Main

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

public class Example
{
   public static void Main()
   {
      DateTime date = new DateTime(2011, 3, 1);
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"), 
                                 new CultureInfo("fr-FR") };

      foreach (var culture in cultures)
         Console.WriteLine("{0,-12} {1}", String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.ToString("d", culture));                                    
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:19,代码来源:String

输出:

Invariant    03/01/2011
en-US        3/1/2011
fr-FR        01/03/2011


示例17: Main

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

public class Example
{
   public static void Main()
   {
      string dateString = "07/10/2011";
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 CultureInfo.CreateSpecificCulture("en-GB"), 
                                 CultureInfo.CreateSpecificCulture("en-US") };
      Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture", 
                                                 "Month", "Day");
      foreach (var culture in cultures) {
         DateTime date = DateTime.Parse(dateString, culture);
         Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, 
                           String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.Month, date.Day);
      }                      
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:23,代码来源:String

输出:

Date String     Culture    Month      Day

07/10/2011    Invariant        7       10
07/10/2011        en-GB       10        7
07/10/2011        en-US        7       10


示例18: Main

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

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture));
      Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:14,代码来源:String

输出:

1
-32


示例19: Main

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

public class CompareStringSample
{
   public static void Main()
   {
      string str1 = "Apple";
      string str2 = "Æble"; 
      string str3 = "AEble";
      
      // Set the current culture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Set the current culture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Perform an ordinal comparison.
      Console.WriteLine("Ordinal comparison");
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, 
                        String.Compare(str1, str2, StringComparison.Ordinal));
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, 
                        String.Compare(str2, str3, StringComparison.Ordinal));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:41,代码来源:String

输出:

Current culture: da-DK
Comparison of Apple with Æble: -1
Comparison of Æble with AEble: 1

Current culture: en-US
Comparison of Apple with Æble: 1
Comparison of Æble with AEble: 0

Ordinal comparison
Comparison of Apple with Æble: -133
Comparison of Æble with AEble: 133


示例20: Main

//引入命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
 
public class Example
{
   public static void Main()
   {
      string[] strings = { "coop", "co-op", "cooperative", 
                           "co\u00ADoperative", "cœur", "coeur" };

      // Perform a word sort using the current (en-US) culture.
      string[] current = new string[strings.Length]; 
      strings.CopyTo(current, 0); 
      Array.Sort(current, StringComparer.CurrentCulture);

      // Perform a word sort using the invariant culture.
      string[] invariant = new string[strings.Length];
      strings.CopyTo(invariant, 0); 
      Array.Sort(invariant, StringComparer.InvariantCulture);

      // Perform an ordinal sort.
      string[] ordinal = new string[strings.Length];
      strings.CopyTo(ordinal, 0); 
      Array.Sort(ordinal, StringComparer.Ordinal);

      // Perform a string sort using the current culture.
      string[] stringSort = new string[strings.Length];
      strings.CopyTo(stringSort, 0); 
      Array.Sort(stringSort, new SCompare());

      // Display array values
      Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n", 
                        "Original", "Word Sort", "Invariant Word", 
                        "Ordinal Sort", "String Sort");
      for (int ctr = 0; ctr < strings.Length; ctr++)
         Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                           strings[ctr], current[ctr], invariant[ctr], 
                           ordinal[ctr], stringSort[ctr] );          
   }
}

// IComparer<String> implementation to perform string sort.
internal class SCompare : IComparer<String>
{
   public int Compare(string x, string y)
   {
      return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:52,代码来源:String

输出:

Original     Word Sort  Invariant Word  Ordinal Sort   String Sort

coop          cœur            cœur         co-op         co-op
co-op         coeur           coeur         coeur          cœur
cooperative          coop            coop          coop         coeur
co­operative         co-op           co-op   cooperative          coop
cœur   cooperative     cooperative  co­operative   cooperative
coeur  co­operative    co­operative          cœur  co­operative



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# StringComparer类代码示例发布时间:2022-05-24
下一篇:
C# StackOverflowException类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap