如何用“和”替换最后一个逗号

时间:2018-02-27 10:23:38

标签: c#

我想在我的C#示例中用"and"替换最后一个逗号,并在结尾处完全停止。

我正在尝试以下代码:

result = (result.LastIndexOf(",") == result.Length - 2) 
        ? result.Remove(result.LastIndexOf(","), 2) 
        : result;

result += ".";

我的当前输出是这样的:

  

abc,def,ghi。

预期:

  
    

abc,def和ghi。

  

我需要用and替换最后一个昏迷。我尝试使用replace,但它没有用。

5 个答案:

答案 0 :(得分:3)

这是一种(天真的)方式:

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

注意此代码如何重复LastIndexOf(',') 3次?这可以通过使用变量来修复。另外,正如Ian H在他的评论中写道,我们应该验证字符串中至少有一个,,所以这里是最终版本:

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

答案 1 :(得分: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" 

答案 2 :(得分: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);

答案 3 :(得分:1)

        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 :(得分:0)

这可能是矫kill过正,但是鉴于替换最后一次出现的事情是一项常见的任务,我想到了使用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 Here