C# StartsWith() 方法


C# 中的 StartsWith() 方法用於判斷此字串例項的開頭是否與指定字串匹配。

語法

public bool StartsWith (string val);

上面,val 是要比較的字串。

示例

 線上演示

using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      Console.WriteLine("Does String begins with J? = "+str.StartsWith("J"));
      char[] destArr = new char[20];
      str.CopyTo(1, destArr, 0, 4);
      Console.Write(destArr);
   }
}

輸出

這將產生以下輸出 -

String = JohnAndJacob
Does String begins with J? = True
ohnA

示例

我們現在看另一個示例 -

 線上演示

using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Akon";
      string str2 = "Eminem";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E"));
      Console.WriteLine("
String 2 = "+str2);       Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());       Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E"));       Console.WriteLine("
String 1 is equal to String 2? = {0}", str1.Equals(str2));    } }

輸出

這將產生以下輸出 -

String 1 = Akon
HashCode of String 1 = 416613838
Does String1 begins with E? = False
String 2 = Eminem
HashCode of String 2 = 40371907
Does String2 begins with E? = True
String 1 is equal to String 2? = False

更新時間: 03-12-2019

894 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.