简体   繁体   English

提取字符串某些部分的最有效方法是什么?

[英]What is the most efficient way to extract certain parts of a string?

I have the following object: 我有以下对象:

public class Color
{
   public string RGB = "000225123";

}

I need to be able to parse out the R,G, and B components, but they may not be in that exact, however, I will know the order. 我需要能够解析出R,G和B组件,但它们可能不完全相同,但是我会知道顺序。 So one way, it might be RGB , but another way it might be RBG . 因此,一种方法可能是RGB ,但另一种方法可能是RBG

I thought about something like this: 我想到了这样的事情:

string G =  RGB.Substring(RGB.IndexOf('2'),3);

but here I happen to know where the G starts and ends, so I can hard-code it, which leads me to another question of what is the best way to store the order. 但是在这里我碰巧知道G的起点和终点,因此我可以对其进行硬编码,这又引出了另一个问题,即最好的存储订单方式。 I have thought about doing something like: 我已经考虑过要做类似的事情:

string order = "RGB";

string RGB = "000225123";

string R = RGB.Substring(order.IndexOf('R'),3);

The above works, but what about the scenario where each part can be a varied length, so R can be 2 or 3 characters for example, would that be something I store separately or would I store it within the order? 上面的方法有效,但是每个部分的长度可以变化的情况如何,例如R可以是2个或3个字符,那是我要单独存储还是将其存储在订单中?

I might have a number like this: 我可能会有这样的数字:

28-34-29-000-00.0

or it could be in the order 或者可能是顺序

29-34-28-000-00.0

In the above the 28 and 29 are switched and I will know this order, I will just need to know how to parse it out. 在上面的2829进行了切换,我将知道此顺序,我只需要知道如何解析它即可。

Here is a more realistic scenario and solution, but I am not sure if it is efficient enough: 这是一个更现实的方案和解决方案,但是我不确定它是否足够有效:

string order = "TSR"; 字符串顺序=“ TSR”;

string value = "20-10-28-0000-0011";

string[] tokens = value .Split('-');

string t= tokens[order.IndexOf('T')];

string s= tokens[order.IndexOf('S')];

string r= tokens[order.IndexOf('R')];

I would create an interface which contains a method to parse. 我将创建一个包含要解析的方法的接口。

Eg, 例如,

IParseColorString
{
  ColorParts Parse(String s);
}

ColorParts
{
  public string R {get;}
  public string G {get;}
  public String B {get;}
  // or if you wanted the int directly have int return type instead of string
}

Then have all the classes with the appropriate ordering derive the interface: 然后让所有具有适当顺序的类派生该接口:

ParseRGB : IParseColorString
{
    public ColorParts Parse(String s)
    {
       //  parsing logic for RGB
    }
}

ParseRBG : IParseColorString
{
  public ColorParts Parse(String s)
  {
     // parsing logic for RBG
  }
}

Then use them as you like. 然后根据需要使用它们。 You can even have a factory which has them as static instances 您甚至可以拥有一个将其作为静态实例的工厂

ColorParsingFactory
{
    public static IParseColorString ParseRGB {get{/* gets the RGB parser */}}
    public static IParseColorString ParseRBG {get{/* gets the RBG parser */}}
}

You can use a function like this to extract a component from a string: 您可以使用如下函数从字符串中提取组件:

public static int GetComponent(string data, string format, char component) {
  return Int32.Parse(new String(data.Where((c, i) => format[i] == component).ToArray()));
}

Usage: 用法:

string color = "000225123";
string format = "RRRGGGBBB";

int red = GetComponent(color, format, 'R');
int green = GetComponent(color, format, 'G');
int blue = GetComponent(color, format, 'B');

It would work for any format that you can describe that way: 它适用于您可以描述的任何格式:

string time = "2012-10-12 19:02";
string format = "YYYY MM DD hh mm";

int year = GetComponent(time, format, 'Y');
int month = GetComponent(time, format, 'M');
int day = GetComponent(time, format, 'D');
int hour = GetComponent(time, format, 'h');
int minute = GetComponent(time, format, 'm');

A better way to convert a color to a number is to use the ARGB-Format 将颜色转换为数字的更好方法是使用ARGB格式

Color c = Color.Aquamarine;
// Or if you have R-G-B values:  Color c = Color.FromArgb(111,222,333);
int argb = c.ToArgb(); // --> -8388652
string s = argb.ToString(); // --> "-8388652"

// Backwards
argb = Int32.Parse(s);
c = Color.FromArgb(argb);

int R = c.R;
int G = c.G;
int B = c.B;

UPDATE: 更新:

A simple way to store it as string by maintaining the RGB-parts would be 通过维护RGB部分将其存储为字符串的简单方法是

string s1 = "RGB;123;255;77";
string s2 = "RBG;123;77;255";

string[] parts = s1.Split(';');

int r, g, b;
switch (parts[0]) {
    case "RGB":
        r = Int32.Parse(parts[1]);
        g = Int32.Parse(parts[2]);
        b = Int32.Parse(parts[3]);
        break;
    case "RBG":
        r = Int32.Parse(parts[1]);
        b = Int32.Parse(parts[2]);
        g = Int32.Parse(parts[3]);
        break;
    default:
        r = 0;
        b = 0;
        g = 0;
        break;
}

Since you know the order, you can get values by using the string indexer . 由于知道顺序,因此可以使用字符串索引器获取值。

Example blatantly stolen from MSDN: 从MSDN失窃的示例:

string str1 = "Test";
for (int ctr = 0; ctr <= str1.Length - 1; ctr++ )
   Console.Write("{0} ", str1[ctr]);

// The example displays the following output: 
//      T e s t         

You might also want to look into System.Drawing.Color . 您可能还需要研究System.Drawing.Color If it's really colors you are parsing you don't even need to define your own structure. 如果您要解析的是真正的颜色,则甚至无需定义自己的结构。

If I understand correctly, there's some other service that could give you an order and an RGB string? 如果我理解正确,还有其他服务可以为您提供订单和RGB字符串吗?

In that case, let's try to store types faithfully and convert data upon arrival . 在这种情况下,让我们尝试如实存储类型在到达时转换数据

public class Color{

public int R{
    get;
    set; 
    }


public int G{
    get;
    set; 
    }

public int B{
    get;
    set; 
    }

public Color(string mixedRGB, string order){
    R = Int32.Parse(mixedRGB.Substring(order.IndexOf('R'),3));
    G = Int32.Parse(mixedRGB.Substring(order.IndexOf('G'),3));
    B= Int32.Parse(mixedRGB.Substring(order.IndexOf('B'),3));
}

This will save you space if you have memory constraints and save you sanity from preventing nonsensical values assigned to your objects. 如果您有内存限制,这将节省您的空间,并且可以避免分配给您的对象的无意义的值。 (What color does the RGB string "DF)_3nAv1" make?) (RGB字符串“ DF)_3nAv1”是什么颜色的?)

You'll know what values correspond to R, G, and B because you store them seperately. 您将知道分别与R,G和B对应的值,因为它们分别存储。 IF you need to combine them frequently, you could make a function in this class to combine them. 如果需要经常组合它们,则可以在此类中创建一个函数来组合它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM