String類的幾個方法的應用示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str1 = "Dood morning!";
string str2 = "How are you?";
//輸出兩個字串
Console.WriteLine(str1);
Console.WriteLine(str2);
//輸出兩個字串的長度
Console.WriteLine("字串str1的長度為{0}", str1.Length);
Console.WriteLine("字串str2的長度為{0}", str2.Length);
//比較字串的長度
Console.WriteLine(str1.CompareTo(str2));
//判斷字串是否相等
Console.WriteLine(str1.Equals(str2));
//輸出和給定字串在原字串中的位置
Console.WriteLine("字串\"are\"在str2中的位置是:{0}", str2.IndexOf("are"));
//輸出和給定字串在原字串中最后出現的位置
Console.WriteLine("字串\"are\"在str2中最后出現出現的位置是:{0}", str2.LastIndexOf("are"));
//判斷字串是否以給定字串開始
Console.WriteLine(str1.StartsWith("Good"));
//判斷字串是否以給定字串結尾
Console.WriteLine(str1.EndsWith("morning"));
//提取字串,從第五位開始,提取七個字符,輸出新字串
Console.WriteLine(str1.Substring(5, 7));
//在原字串中從第八位開始,插入給定字串
Console.WriteLine(str1.Insert(8, "hello"));
//從原字串的第六位開始,洗掉三個字符
Console.WriteLine(str1.Remove(6, 3));
//去掉字串前后的空格
Console.WriteLine(str1.Trim());
Console.ReadLine();
}
}
}
運行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/120884.html
標籤:C#
上一篇:型別和變數(C#學習筆記02)
