gpt4 book ai didi

c# - 在 c# 中反转字符串中的单词,保持空格数相同

转载 作者:行者123 更新时间:2023-11-30 20:23:05 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来反转 c# 中字符串中的单词, 例如:“这是一些文本, Hello World ”
应该打印成 “world hello, text some is This”反向字符串中的空格数必须相同,逗号等特殊字符必须正确放置在前面的单词之后,如反向字符串中所示。我试过跟随,但它没有处理像 ',' 这样的特殊字符

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;


}

最佳答案

什么意思

with special characters like comma

还有其他需要区别对待的角色吗?这会将 "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(" ", ", ");

更新

如果您想处理每个特殊字符,您需要一个 RegEx 解决方案。

string result2 =string.Join(string.Empty,  System.Text.RegularExpressions.Regex.Split(input, @"([^\w]+)").Reverse());

关于c# - 在 c# 中反转字符串中的单词,保持空格数相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29911619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com