[英]reverse words in a string in c# keeping number of whitespaces same
我正在嘗試編寫一個函數來反轉c#中的字符串中的單詞,例如:“這是一些文本,您好世界”
應該像“世界你好,文本有些是這樣”那樣打印。反向字符串中的空格數必須相同,並且必須正確地將特殊字符(如逗號)放在反向字符串中顯示的前一個單詞之后。 我嘗試了以下操作,但沒有處理諸如','之類的特殊字符
public static string reverseStr(string s)
{
string result = "";
string word = "";
foreach (char c in s)
{
if (c == ' ')
{
result = word + ' ' + result;
word= "";
}
else
{
word = word + c;
}
}
result = word + ' ' + result;
return result;
}
你什么意思
帶有逗號等特殊字符
還有其他字符需要區別對待嗎? 這將變成"This is some text, hello world"
到您的預期結果"This is some text, hello world"
"world hello, text some is This"
string input = "This is some text, hello world";
string result = string.Join(" ", input.Split(' ', ',').Reverse()).Replace(" ", ", ");
UPDATE
如果要處理每個特殊字符,則需要RegEx解決方案。
string result2 =string.Join(string.Empty, System.Text.RegularExpressions.Regex.Split(input, @"([^\w]+)").Reverse());
這是使用正則表達式的解決方案:
Regex.Replace(
string.Join("", //3. Join reversed elements
Regex.Split(input, @"(\s+)|(,)") //1. Split by space and comma, keep delimeters
.Reverse()), //2. Reverse splitted elements
@"(\s+),", @",$1"); //4. Fix comma position in joined string
以下解決方案保留所有空格。
它首先檢測任何字符的種類(分隔符與單詞/內容),並存儲一個塊列表(其中每個項目都包含開始和結束索引,以及一個布爾值,告訴布爾塊是否包含分隔符或單詞)。
然后,它將塊以相反的順序寫入結果字符串。
每個塊內的字符順序得以保留,即作為分隔符或單詞/內容的塊:這也允許保留任何雙倍空格或其他分隔符鏈,而無需后檢查其順序或數量。
public static string Reverse(string text, Func<char, bool> separatorPredicate)
{
// Get all chars from source text
var aTextChars = text.ToCharArray();
// Find the start and end position of every chunk
var aChunks = new List<Tuple<int, int, bool>>();
{
var bLast = false;
var ixStart = 0;
// Loops all characters
for (int ixChar = 0; ixChar < aTextChars.Length; ixChar++)
{
var ch = aTextChars[ixChar];
// Current char is a separator?
var bNow = separatorPredicate(ch);
// Current char kind (separator/word) is different from previous
if ((ixChar > 0) && (bNow != bLast))
{
aChunks.Add(Tuple.Create(ixStart, ixChar - 1, bLast));
ixStart = ixChar;
bLast = bNow;
}
}
// Add remaining chars
aChunks.Add(Tuple.Create(ixStart, aTextChars.Length - 1, bLast));
}
var result = new StringBuilder();
// Loops all chunks in reverse order
for (int ixChunk = aChunks.Count - 1; ixChunk >= 0; ixChunk--)
{
var chunk = aChunks[ixChunk];
result.Append(text.Substring(chunk.Item1, chunk.Item2 - chunk.Item1 + 1));
}
return result.ToString();
}
public static string Reverse(string text, char[] separators)
{
return Reverse(text, ch => Array.IndexOf(separators, ch) >= 0);
}
public static string ReverseByPunctuation(string text)
{
return Reverse(text, new[] { ' ', '\t', '.', ',', ';', ':' });
}
public static string ReverseWords(string text)
{
return Reverse(text, ch => !char.IsLetterOrDigit(ch));
}
有四種方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.