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 @   似梦亦非梦  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示