CharEnumerator.Clone方法用於創建當前CharEnumerator對象的副本。這對於在迭代String對象時保存當前狀態很有用。
用法:
public object Clone ();
返回值:此方法返回一個Object,它是當前CharEnumerator對象與CharEnumerator對象的當前狀態的副本。
以下示例程序旨在說明CharEnumerator.Clone()方法的使用:
示例1:
// C# program to illustrate the
// CharEnumerator.Clone Method
using System;
class GFG {
// Driver code
public static void Main()
{
// Initialize a string object
string str = "The Sun rises in the East,sets in the West.";
// Instantiate a CharEnumerator object
CharEnumerator chEnum = str.GetEnumerator();
while (chEnum.MoveNext())
{
// Printing the characters
Console.Write(chEnum.Current);
// Break when a space is encountered
if (chEnum.Current == ',')
{
Console.WriteLine();
break;
}
}
// Instantiate a copy of CharEnumerator
// object with the current state
CharEnumerator chEnumCopy = (CharEnumerator)chEnum.Clone();
// Printing the rest of the characters
while (chEnumCopy.MoveNext())
Console.Write(chEnumCopy.Current);
}
}
輸出:
The Sun rises in the East, sets in the West.
示例2:
// C# program to illustrate the
// CharEnumerator.Clone Method
using System;
class GFG {
// Driver code
public static void Main()
{
// Initialize a string object
string str = "1234567";
// Instantiate a CharEnumerator object
CharEnumerator chEnum = str.GetEnumerator();
while (chEnum.MoveNext())
{
// Print current character
Console.Write(chEnum.Current + " ");
// Instantiate a copy of CharEnumerator
// object with current state
CharEnumerator chEnumCopy = (CharEnumerator)chEnum.Clone();
// Printing all characters
// after the current position
while (chEnumCopy.MoveNext())
Console.Write(chEnumCopy.Current + " ");
Console.WriteLine();
}
}
}
輸出:
1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 C# | CharEnumerator.Clone() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。