[英]How to reverse a string without using built-in c# method
I want to know how to reverse a string in C# without using any .NET built-in methods.我想知道如何在不使用任何 .NET 内置方法的情况下在 C# 中反转字符串。
My initial code:我的初始代码:
Console.WriteLine("Please enter a string");
string myString = Console.ReadLine();
The idea is to reverse the string named myString
, which we are getting via the User's Console Input.这个想法是反转名为
myString
的字符串,我们通过用户的控制台输入获得它。
If you are trying to reverse a string that contains only English letters (I presume since your answer contains no methods to handle other letters), you could simplify your code by doing something like this:如果您试图反转仅包含英文字母的字符串(我认为因为您的答案不包含处理其他字母的方法),您可以通过执行以下操作来简化您的代码:
private static string ReverseString(string myString)
{
string reversedString = string.Empty;
for (int i = myString.Length - 1; i >= 0 ; i--)
{
reversedString += myString[i];
}
return reversedString;
}
This method, obviously, doesn't contain any way to handle non-English letters, it is just a simplification of your answer.显然,这种方法不包含任何处理非英文字母的方法,它只是您答案的简化。
We can convert the string to a char array and reverse the array.我们可以将字符串转换为字符数组并反转数组。 Given an array of size N, we only need to iterate in a loop for N/2 times while swapping the characters from the end of the array with the ones in the beginning.
给定一个大小为 N 的数组,我们只需要在循环中迭代 N/2 次,同时将数组末尾的字符与开头的字符交换。 We can start from the beginning and ending characters, swap those and then move inwards with each iteration, until we reach the middle of the array.
我们可以从开始和结束字符开始,交换它们,然后在每次迭代中向内移动,直到到达数组的中间。
public static string Reverse(string input)
{
var inputArray = input.ToCharArray();
var end = inputArray.Length / 2;
for (int i = 0; i < end; i++)
{
var temp = inputArray[i];
inputArray[i] = inputArray[inputArray.Length - i - 1];
inputArray[inputArray.Length - i - 1] = temp;
}
var result = new string(inputArray);
return result;
}
convert it to a character array, reverse, convert to string.将其转换为字符数组,反向,转换为字符串。 (that is how i would do it in java).
(这就是我在 Java 中的做法)。
We can use the procedure below to reverse the String.我们可以使用下面的过程来反转字符串。
string myString = Console.ReadLine();
char[] charStr = new char[str.Length];
int k = charStr.Length - 1;
for (int i=0;i<charStr.Length;i++)
{
int j = k;
while (j>=0)
{
charStr[j] = str[i];
j--;
}
k--;
}
foreach (char item in charStr)
{
Console.Write(item);
}
Console.WriteLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.