在不使用反向函数的情况下反转给定的字符串

本文关键字:情况下 字符串 函数 | 更新日期: 2023-09-27 18:31:08

我想在不使用 c# 中的字符串函数的情况下反转给定的字符串。

例如:I有"欢迎来到世界"我要这样反转:"世界欢迎"

在不使用反向函数的情况下反转给定的字符串

通过使用 Regex es :-)

var str = "Welcome to the world";
var parts = System.Text.RegularExpressions.Regex.Split(str, " ");
Array.Reverse(parts);
var sb = new StringBuilder();
foreach (var part in parts)
{
    sb.Append(part);
    sb.Append(' ');
}
if (sb.Length > 0)
{
    sb.Length--;
}
var str2 = sb.ToString();

请注意,Regex (es) 不是 System.String 类的一部分 :-) :-)(他们System.Text.RegularExpressions.Regex

徒劳的,但是,

public string GetReversedWords(string source)
{
    var word = new StringBuilder(source.Length);
    var result = new StringBuilder(source.Length);
    var first = true;
    foreach (var c in source.Reverse())
    {
        if (c.IsWhiteSpace)
        {
            first = WriteReverseWord(result, word, first);
            word.Clear();
            continue;
        }
        word.Append(c);
    }
    WriteReverseWord(result, word, first);
    return result.ToString();
}
private static bool WriteReverseWord(
    StringBuilder output,
    StringBuilder word,
    bool first)
{
    if (word.Length == 0)
    {
        return first;
    }
    if (!first)
    {
        output.Append(' ');
    }
    for (var i = word.Length -1; i > -1; i--)
    {
        output.Append(word[i]);
    }
    return false;
}

这可以使用 LINQ 非常容易地完成,如下所示:

 string str = "Welcome to the world";
 string[] arr = str.Split(' ').Reverse().ToArray();
 Console.WriteLine(string.Join(" ",arr)); //Prints "world the to welcome"

Reference-VeeQuest

/**Reverse a Sentence without using C# inbuilt functions
 (except String.Length property, m not going to write code for this small functionality )*/
const char EMPTYCHAR = ' ';
const string EMPTYSTRING = " ";
/// <summary>
/// Reverse a string Sentence
/// </summary>
/// <param name="pStr"></param>
/// <returns></returns>
public string ReverseString(string pStr)
{
  if (pStr.Length > 1) //can be checked/restricted via validation
  {
    string strReversed = String.Empty;
    string[] strSplitted = new String[pStr.Length];
    int i;
    strSplitted = Split(pStr); // Complexity till here O(n)
    for (i = strSplitted.Length - 1; i >= 0; i--)
    // this for loop add O(length of string) in O(n) which is similar to O(n)
    {
        strReversed += strSplitted[i];
    }
    return strReversed;
  }
  return pStr;
}
/// <summary>
/// Split the string into words & empty spaces
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string[] Split(string str)
{
    string strTemp = string.Empty;
    string[] strArryWithValues = new String[str.Length];
    int j = 0;
    int countSpace = 0;
    //Complexity of for conditions result to O(n)
    foreach (char ch in str)
    {
        if (!ch.Equals(EMPTYCHAR))
        {
            strTemp += ch; //append characters to strTemp
            if (countSpace > 0)
            {
                strArryWithValues[j] = ReturnSpace(countSpace); // Insert String with Spaces
                j++;
                countSpace = 0;
            }
        }
        else
        {
            countSpace++;
            if (countSpace == 1)
            {
                strArryWithValues[j] = strTemp; // Insert String with Words
                strTemp = String.Empty;
                j++;
            }
        }
    }
    strArryWithValues[j] = strTemp;
    return (strArryWithValues);
}
/// <summary>
/// Return a string with number of spaces(passed as argument)
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public string ReturnSpace(int count)
{
    string strSpaces = String.Empty;
    while (count > 0)
    {
        strSpaces += EMPTYSTRING;
        count--;
    }
    return strSpaces;
}
/************Reverse Sentence Ends***************/
相关文章: