{"title":"C# 去除字符串左右空格,不使用等号运算符 - 代码示例","description":"本文提供了一个 C# 代码示例,演示了如何使用循环和 Substring 方法,不使用等号运算符,来去除字符串左右空格。","keywords":"C#,字符串,去除空格,Trim,循环,Substring,代码示例","content":"以下是一种不使用等号运算符的方法来去掉字符串左右空格的示例代码:\n\ncsharp\nusing System;\n\npublic class Program\n{\n public static void Main(string[] args)\n {\n string input = " Hello, World! ";\n string trimmed = RemoveWhitespace(input);\n \n Console.WriteLine(trimmed);\n }\n \n public static string RemoveWhitespace(string input)\n {\n string whitespace = " \t\n\r";\n \n int start = 0;\n while (whitespace.Contains(input[start]))\n {\n start++;\n }\n \n int end = input.Length - 1;\n while (whitespace.Contains(input[end]))\n {\n end--;\n }\n \n int length = end - start + 1;\n return input.Substring(start, length);\n }\n}\n\n\n在这个例子中,我们使用了两个 while 循环来找到字符串的开始和结束位置,这些位置是不包含空格的。然后,我们使用 Substring 方法来提取从开始位置到结束位置的子字符串,这样就得到了去掉左右空格的结果。"}

C# 去除字符串左右空格,不使用等号运算符 - 代码示例

原文地址: http://www.cveoy.top/t/topic/qao1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录