![](/img/trans.png)
[英]Reverse the words in a string without using builtin functions like split and substring in C#
[英]Reverse words of a sentence without using String.Split in C#
最近,有人在討論中要求我編寫一種算法,以實現句子中單詞的反向(不是整個句子的反向),而不使用諸如ToCharArray和Length之外的字符串操作,例如Split / Replace / Reverse / Join。 以下是我可以在5分鍾的時間內設計的內容。 盡管該算法運行良好,但實現方式似乎有點難看。 某些機構可以通過完善代碼來幫助我。
string ReverseWords(string s)
{
string reverseString = string.Empty;
string word = string.Empty;
var chars = s.ToCharArray();
List<ArrayList> words = new List<ArrayList>();
ArrayList addedChars = new ArrayList();
Char[] reversedChars = new Char[chars.Length];
int i = 1;
foreach (char c in chars)
{
if (c != ' ')
{
addedChars.Add(c);
}
else
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
if (i == s.Length)
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
i++;
}
foreach (ArrayList a in words)
{
for (int counter = a.Count - 1; counter >= 0; counter--)
{
reverseString += a[counter];
}
if(reverseString.Length < s.Length)
reverseString += " ";
}
return reverseString;
}
有 一種使用LIFO堆棧相對簡潔的解決方案 。
但是,問題聽起來像是作業,所以我只提供偽代碼。
currWord = new LIFO stack of characters
while (! end of string/array)
{
c = next character in string/array
if (c == some_white_space_character) {
while (currWord not empty) {
c2 = currWord.pop()
print(c2)
}
print(c)
}
else
currWord.push(c)
}
這有點簡單:
string inp = "hai how are you?";
StringBuilder strb = new StringBuilder();
List<char> charlist = new List<char>();
for (int c = 0; c < inp.Length; c++ )
{
if (inp[c] == ' ' || c == inp.Length - 1)
{
if (c == inp.Length - 1)
charlist.Add(inp[c]);
for (int i = charlist.Count - 1; i >= 0; i--)
strb.Append(charlist[i]);
strb.Append(' ');
charlist = new List<char>();
}
else
charlist.Add(inp[c]);
}
string output = strb.ToString();
拋光版本的種類:-
string words = "hi! how are you!";
string reversedWords = "";
List<int> spaceEncounter = new List<int>();
spaceEncounter.Add(words.Length - 1);
for (int i = words.Length - 1; i > 0; i--)
{
if(words[i].Equals(' '))
{
spaceEncounter.Add(i);
for (int j = i+1; j < spaceEncounter[spaceEncounter.Count - 2]; j++)
reversedWords += words[j];
reversedWords += " ";
}
}
for (int i = 0; i < spaceEncounter[spaceEncounter.Count - 1]; i++)
reversedWords += words[i];
在C#中使用堆棧
string str = "ABCDEFG";
Stack<char> stack=new Stack<char>();
foreach (var c in str)
{
stack.Push(c);
}
char[] chars=new char[stack.Count];
for (int i = 0; i < chars.Length; i++)
{
chars[i]=stack.Pop();
}
var result=new string(chars); //GFEDCBA
您的代碼中有一個小錯誤。 因此,輸出字符串將顯示為yo are how hi!
,給定輸入字符串hi! how are you
hi! how are you
。 它會截斷最后一個單詞的最后一個字符。
更改此:
spaceEncounter.Add(words.Length - 1);
至:
spaceEncounter.Add(words.Length);
好吧,您沒有對其他LINQ擴展方法說什么:)
static string ReverseWordsWithoutSplit(string input)
{
var n = 0;
var words = input.GroupBy(curr => curr == ' ' ? n++ : n);
return words.Reverse().Aggregate("", (total, curr) => total + string.Concat(curr.TakeWhile(c => c != ' ')) + ' ');
}
string temp = string.Empty;
string reversedString = string.Empty;
foreach (var currentCharacter in testSentence)
{
if (currentCharacter != ' ')
{
temp = temp + currentCharacter;
}
else
{
reversedString = temp + " " + reversedString;
temp = string.Empty;
}
}
reversedString = temp + " " + reversedString;
此版本可就地工作,沒有任何中間數據結構。 首先,它反轉每個單詞中的字符。 “我也是” =>“ em oot”。 然后它反轉整個字符串:“ em oot” =>“ too me”。
public static string ReverseWords(string s)
{
if (string.IsNullOrEmpty(s))
return s;
char[] chars = s.ToCharArray();
int wordStartIndex = -1;
for (int i = 0; i < chars.Length; i++)
{
if (!Char.IsWhiteSpace(chars[i]) && wordStartIndex < 0)
{
// Remember word start index
wordStartIndex = i;
}
else
if (wordStartIndex >= 0 && (i == chars.Length-1 || Char.IsWhiteSpace(chars[i + 1]))) {
// End of word detected, reverse the chacacters in the word range
ReverseRange(chars, wordStartIndex, i);
// The current word is complete, reset the start index
wordStartIndex = -1;
}
}
// Reverse all chars in the string
ReverseRange(chars, 0, chars.Length - 1);
return new string(chars);
}
// Helper
private static void ReverseRange(char[] chars, int startIndex, int endIndex)
{
for(int i = 0; i <= (endIndex - startIndex) / 2; i++)
{
char tmp = chars[startIndex + i];
chars[startIndex + i] = chars[endIndex - i];
chars[endIndex - i] = tmp;
}
}
一個簡單的遞歸函數如何檢查“”,然后相應地子字符串呢?
private static string rev(string inSent) {
if(inSent.IndexOf(" ") != -1)
{
int space = inSent.IndexOf(" ");
System.Text.StringBuilder st = new System.Text.StringBuilder(inSent.Substring(space+1));
return rev(st.ToString()) + " " + inSent.Substring(0, space);
}
else
{
return inSent;
}
}
最簡單的答案之一如下所示,請仔細閱讀,
public static string ReversewordString(string Name)
{
string output="";
char[] str = Name.ToCharArray();
for (int i = str.Length - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
output = output + " ";
for (int j = i + 1; j < str.Length; j++)
{
if (str[j] == ' ')
{
break;
}
output=output+ str[j];
}
}
if (i == 0)
{
output = output +" ";
int k = 0;
do
{
output = output + str[k];
k++;
} while (str[k] != ' ');
}
}
return output;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.