如何用 "and" 替换最后一个逗号

5
我想在我的C#示例中将最后一个逗号替换为"and",并在结尾处加上句号。
我正在尝试以下代码:
result = (result.LastIndexOf(",") == result.Length - 2) 
        ? result.Remove(result.LastIndexOf(","), 2) 
        : result;

result += ".";

我的当前输出如下:

abc, def, ghi。

期望的输出如下:

abc,def和ghi。

我需要用 and 替换最后一个逗号。我尝试使用 replace,但它没有起作用。


4
你是怎样得出== result.Length - 2这个逻辑的? - H H
4
最好的建议是:忘记 ?:,写一个适当的 if() {} - H H
1
@Liam,你有没有意识到这里有两个逗号,而 OP 只想替换最后一个? - René Vogt
1
你是如何构建结果的?与其修复已创建的字符串,我们可以帮助构建正确的字符串。 - Tim Schmelter
我的结果是从一个包含许多日志的字符串中解析出来的,我正在从中提取特定的数据。 - Justin
显示剩余2条评论
6个回答

10
var test = "Service Control Manager repeated 5 times, " +
    "Microsoft-Windows-DistributedCOM repeated 2 times, " +
    "Control Manager repeated 6 times.";
var lastComma = test.LastIndexOf(',');
if (lastComma != -1) test = test.Remove(lastComma, 1).Insert(lastComma, " and");

4
这里有一种(天真的)方法来实现它:
result = result.Substring(0, result.LastIndexOf(',')) 
         + " and" 
         + result.Substring(result.LastIndexOf(',')+1);

这是一种天真的做法,因为它假定字符串中至少有一个,字符,且该字符不是该字符串的最后一个字符。

因此,您需要将其放在一个条件语句中:

if(result.LastIndexOf(',') < result.Length-1)
{
    result = result.Substring(0, result.LastIndexOf(',')) 
             + " and" 
             + result.Substring(result.LastIndexOf(',')+1);
}

您是否注意到这段代码中重复了3次LastIndexOf(',')?可以使用一个变量来解决这个问题。另外,正如Ian H在他的评论中提到的那样,我们应该验证字符串中至少有一个,,因此这是最终版本:

var lastComma = result.LastIndexOf(',');
if(lastComma > -1 && lastComma < result.Length - 1)
{
    result = result.Substring(0, lastComma) 
             + " and" 
             + result.Substring(lastComma + 1);
}

你还可以检查结果的最后一个索引是否大于“-1”,以防找不到逗号。 - Ian H.

3

不确定为什么没有人提到正则表达式,这似乎是最短的选项:

string source = "UK, USA, Canada, New Zealand";
string result = Regex.Replace(source, ", ([^,]+)$", " and $1");
Console.WriteLine($"result is {result}");
// UK, USA, Canada and New Zealand


2
为什么不使用Substring函数?
// Let's cache the position in order not to scan several times
int position = result.LastIndexOf(',');

if (position >= 0) // do we have anything to cut out?
  result = result.Substring(0, position).TrimEnd() +    // before 
           " and " +                                    // change , to and
           result.Substring(position + 1).TrimStart();  // after

我建议使用TrimEnd()TrimStart()来获得格式良好的文本:

"a,   b" -> "a and b"
"a  , b" -> "a and b"
"a   ,b" -> "a and b" 

1
这是另一种使用Split的解决方案:

string input = "Service Control Manager repeated 5 times, Microsoft-Windows-DistributedCOM repeated 2 times, Control Manager repeated 6 times.";

string [] allparts = input.Split(',');

string result = string.Join(",", allparts.Take(allparts.Count() -1)) + " and" + allparts.Last();

Console.WriteLine(result);

@Justin,不客气。个人而言,我会使用Zohar Peled的解决方案。它更加直接和直观。 - Mong Zhu

1

这可能有点过度,但考虑到替换最后一个出现的内容是一项常见任务,我想通过使用String/StringBuilder 扩展方法的方式来解决:

 public static class Extensions
{
    //extension method for StringBuilder (possible becuase StringBuilder has a more configurable Replace method than does String). 
    public static StringBuilder ReplaceLastOccurenceOf (this StringBuilder sb, string thingToReplace, string replacement)
        {
            return sb.Replace(thingToReplace, replacement, sb.ToString().LastIndexOf(thingToReplace), thingToReplace.Length);
        }

    // The extension method for string actually calls on the one for StringBuilder, converting it back to string at the end
    public static string ReplaceLastOccurenceOf (this string s, string thingToReplace, string replacement)
        {
            StringBuilder sb = new StringBuilder() ; sb.Append(s); //create the SB instance and give it the string's val
            return sb.ReplaceLastOccurenceOf(thingToReplace, replacement).ToString(); 
        }
}

并这样称呼它们:
using System;
using System.Text;

public class Program
{
    public static void Main()
    {

        string[] cities = { "London", "Delhi", "Paris", "New York"};

        //work with StringBuilder
        var sbCities = new StringBuilder();
        foreach (string city in cities) { sbCities.Append(city + ", ");}
        sbCities.Remove(sbCities.Length-2, 2); // remove last comma and space

        Console.WriteLine($"sbCities = {sbCities}");
        Console.WriteLine("Cities  you've visited are " + sbCities.ReplaceLastOccurenceOf("Paris", "Karachi").ReplaceLastOccurenceOf(",", " and"));
        Console.WriteLine();

        //now for String
        string stringCities = string.Join(", ", cities);
        Console.WriteLine($"stringCities = {stringCities}");
        Console.WriteLine("Cities  you've visited are " + stringCities.ReplaceLastOccurenceOf("Paris", "Karachi").ReplaceLastOccurenceOf(",", " and"));
        Console.WriteLine();
    }

}

在这里查看Fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接