Domanda

I have a list of strings in format like this:

Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp

I need only the part from comma sign to the first dot sign. For example above it should return this string: IScadaManualOverrideService

Anyone has an idea how can I do this and get substrings if I have list of strings like first one?

È stato utile?

Soluzione 2

Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.

So here is another one

    string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
    var end = text.IndexOf(',');
    var start = text.LastIndexOf('.', end) + 1;
    var result = text.Substring(start, end - start);

Proof woof woof.

Bullet-proof version (ugly)

    string text = "IScadaManualOverrideService";
    //string text = "Services.IScadaManualOverrideService";
    //string text = "IScadaManualOverrideService,";
    //string text = "";
    var end = text.IndexOf(',');
    var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
    var result = text.Substring(start, (end == -1 ? text.Length : end) - start);

Insert this if hacker attack is expected

if(text == null)
    return "Stupid hacker, die!";

Altri suggerimenti

from comma sign to the first dot sign

You mean from dot to comma?

You can split the string by comma first, then split by dot and take the last:

string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
    string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
    string s1 = s.Substring(0, s.IndexOf(","));
    string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
 string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
 int commaIndex = input.IndexOf(',');
 string remainder = input.Substring(0, commaIndex);
 int dotIndex = remainder.LastIndexOf('.');

 string output = remainder.Substring(dotIndex + 1);

This can be written a lot shorter, but for the explanation i think this is more clear

sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last);  // output: IScadaManualOverrideService
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top