【问题标题】:Reversing the given string without using reverse function [closed]在不使用反向函数的情况下反转给定的字符串[关闭]
【发布时间】:2013-09-13 11:09:45
【问题描述】:

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

例如:我有“Welcome to the world”,我想像这样反转:“world the to welcome”

【问题讨论】:

  • 这是面试题还是作业..
  • 请注意,您可能会得到“world the to Welcome”:-)
  • 请展示你迄今为止的努力。免费做我的家庭作业是不受欢迎的,尤其是这些琐碎的问题。
  • 嗯,你可以通过摩擦木棍来生火,但是当你有一个干燥的背包,里面装着各种火柴、打火机和火焰喷射器时,你为什么要这样做呢?你一直都在吗?
  • 你应该把作业放在标题里

标签: c# string


【解决方案1】:

通过使用Regexes :-)

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

【讨论】:

  • 我猜OP的excercise/challenge/homework是直接处理字符串数据结构而不是使用任何其他方法(他可能不知道Regex 也可以这样做)。
  • @KingKing 这告诉我们,当你想制定一些规则时,重要的是要确定规则到底是什么:-)
【解决方案2】:

徒劳的,但是,

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;
}

【讨论】:

  • reverse 实际上是 String.Reverse 吗?
  • @PaulZahra 不,它的IEnumerable.Reverse()string 恰好实现了IEnumerable<char>
【解决方案3】:

这可以使用 LINQ 轻松完成,如下所示:

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

【讨论】:

  • without using string functions :-) Split/Join
【解决方案4】:

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***************/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多