在 C# 中取子字串


Substring 用於獲取 C# 中字串的子部分。為此,我們有 substring() 方法。在 C# 中使用 substring() 方法檢查每個子字串是否存在唯一字元。將其迴圈,直到字串的長度為止。

如果任何子字串與另一個相匹配,則表示字串沒有唯一字元。

你可以嘗試執行以下程式碼來確定一個字串中是否包含所有唯一字元。本示例展示了 Substring() 方法的使用 −

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Demo {

   public bool CheckUnique(string str) {
      string one = "";
      string two = "";

      for (int i = 0; i < str.Length; i++) {
         one = str.Substring(i, 1);
         for (int j = 0; j < str.Length; j++) {
            two = str.Substring(j, 1);
            if ((one == two) && (i != j))
            return false;
         }
      }
      return true;
   }

   static void Main(string[] args) {
      Demo d = new Demo();
      bool b = d.CheckUnique("amit");
      Console.WriteLine(b);

      Console.ReadKey();
   }
}

更新日期: 20-Jun-2020

529 檢視

啟動您的 職業

完成課程取得認證

開始
廣告
© . All rights reserved.