2、在字符串“abc123def456”中,如何新的内存空间中获取到字符串“abcdef

	public class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Hello, World!");


			string original = "abc123def456";
			string result = GetAlphabeticPart(original);
			Console.WriteLine(result); // 输出: abcdef

			Console.ReadKey();
		}

		//方法1
		public static string GetAlphabeticPart(string input)
		{
			StringBuilder sb = new StringBuilder(input.Length);
			foreach (char c in input)
			{
				if (char.IsLetter(c))
				{
					sb.Append(c);
				}
			}
			return sb.ToString();
		}

		//方法2
		public static string GetAlphabeticPart(string input)
		{
			Span<char> buffer = stackalloc char[input.Length];
			int index = 0;
			foreach (char c in input)
			{
				if (char.IsLetter(c))
				{
					buffer[index++] = c;
				}
			}
			return new string(buffer.Slice(0, index));
		}

		//方法3
		public static string GetAlphabeticPart(string input)
		{
			int length = 0;
			foreach (char c in input)
			{
				if (char.IsLetter(c))
				{
					length++;
				}
			}

			return string.Create(length, input, (chars, str) =>
			{
				int index = 0;
				foreach (char c in str)
				{
					if (char.IsLetter(c))
					{
						chars[index++] = c;
					}
				}
			});
		}

	}
posted @ 2024-12-14 11:26  似梦亦非梦  阅读(10)  评论(0编辑  收藏  举报