Вопрос

In a string like this: Last-Name — lives on a road, in south-shore. I am trying to replace all instances of "," & "-" in to " " with only skipping the 2nd instance of "-". I then want to replace the "-" with a ",".
I have currently tried to us this:

var all = node.InnerText.Replace(","," ");
var hyph = all.Replace("—",",").Replace("-",",");

Which works... except it is replacing everything and I am needing the 2nd instance of "—" to remain while all other instances of ",", "—" & "-"'s are changed to " ". So it looks like this when it is done:
(Last, Name , lives on a road in south, shore.).
When I need it to look like: (Last Name , lives on a road in south shore).

Doing some looking around, it seems that IndexOf() is the way to go but I am unsure of how to setup my query. Would I be on the right track using something like this? Or is there a better way to go about this? To be honest I am not entirely sure and I am still learning C# so sorry if this is poorly worded or way off mark.

int position = dash.IndexOf(find);
if (position > 1)
{
return dash;
}
return dash.Substring(1, position) + replace + dash.Substring(postion + find.Length);

In every case it will be:

last name — some text here

or

last name — some-sort of text

or

last-name — more text, here

or

last name — more-text here

Where it just needs to be:

last name, some text here.

Thank you for any help!

Это было полезно?

Решение

Here you go

int firstHyph = all.IndexOf('-'); // find the first hyphen
int secondHyph = all.IndexOf('-', firstHyph + 1); // find the second hyphen
var sb = new StringBuilder(all);
sb[secondHyph] = '#'; // replace the second hyphen with some improbable character
// finally, replace all hyphen and whatever you need and change that 
// "second hyphen" (now sharp) to whatever you want
var result = sb.ToString().Replace("-", " ").Replace("#", ",");    

Другие советы

Do this with regex, look up for search operator and set it to search for everything after the first. Sorry answering this on the phone so I can't look it up at the moment.

A simple and, exclusive solution

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

public class Test
{
    public static void Main()
    {
        string all = Convert.ToString("In every case it will be last name — some text here OR last name — some-sort of text OR last-name — more text, here OR last name — more-text here").Replace(",", " ");
        int hyph1 = all.IndexOf('—');
        int hyph2 = hyph1 + all.Substring(++hyph1).IndexOf('—');
        string partial = all.Substring(0, ++hyph2).Replace("—", " ");
        string res = String.Concat(partial, "—", all.Substring(++hyph2).Replace("—", " ").Replace("-", ","));
        Console.Write(res.ToString());
    }
}

See on the Fiddle:

http://ideone.com/wWCGeA

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top