Sprache: C#
Diese Methode dreht den String um. Bsp:
- aus "Snippet" wird "teppinS"
- aus "RENTNER" wird "RENTNER" :-)
Diese Methode arbeitet rekursiv.
/// <summary>
/// Reverse the string.
/// </summary>
/// <param name="text">The String.</param>
/// <returns></returns>
public static string ReverseString(string text)
{
if (text.Length == 1 || String.IsNullOrEmpty(text))
return text;
else
return ReverseString(text.Substring(1)) + text.Substring(0, 1);
}
/// <summary>
/// Reverse the string.
/// </summary>
/// <param name="text">The String.</param>
/// <returns></returns>
public static string ReverseString(string text)
{
if (text.Length == 1 || String.IsNullOrEmpty(text))
return text;
else
return ReverseString(text.Substring(1)) + text.Substring(0, 1);
}
Alte URL:
/snippet/reverse-string/601
Besser wäre eine nicht rekursive Methode. Nachfolgend eine Methode die als Erweiterung zur String-Klasse implementiert ist.
[code]
///
///
public static class StringExtensions
{
///
///
/// ///
public static string Reverse(this string text)
{
StringBuilder sb = new StringBuilder();
for (int i = text.Length – 1; i >= 0; i–)
sb.Append(text.Substring(i, 1));
return sb.ToString();
}
}
[/code]
Beispielaufruf:
[code]
string s = „Test“;
Console.WriteLine(s.Reverse());
Console.ReadKey();
[/code]
Eine noch bessere Version gibts hier: http://dotnet-snippets.de/dns/string-spiegeln-SID1017.aspx
Möglich wäre auch der Einsatz von Linq:
[code]
string.Concat(„Renter“.Reverse());
[/code]