简体   繁体   English

需要从反斜杠分隔的变量中提取数据

[英]Need to extract data from a variable seperated by back slashes

I have a variable that I need to extract data from separated by a back slash.我有一个变量,我需要从中提取数据,用反斜杠分隔。 My variable data would be我的变量数据是

A\123\FRONT\BACK\49585856 A\123\前\后\49585856

I need to extract the second piece based on the back slashes我需要根据反斜杠提取第二部分

Thanks in advance!提前致谢!

I haven't tried anything yet since I am having trouble finding documention我还没有尝试任何东西,因为我找不到文档

as @rufus said正如@rufus所说

string x = @"A\123\FRONT\BACK\49585856";

string[] b = x.Split('\\');

Console.WriteLine(b[2]);

The method you need is Split您需要的方法是拆分

Split is used to break a delimited string into substrings. Split 用于将定界字符串拆分为子字符串。 You can use either a character array or a string array to specify zero or more delimiting characters or strings.您可以使用字符数组或字符串数组来指定零个或多个定界字符或字符串。 If no delimiting characters are specified, the string is split at white-space characters.如果未指定定界字符,则字符串将在空白字符处拆分。

using System;

public class SplitExample
{
    public static void Main(string[] args)
    {
        const char separator = '\\';
        string data = @"A\123\FRONT\BACK\49585856";
        
        string[] myVariables = data.Split(separator);
        
        Console.WriteLine(myVariables[1]); // myVariables[1] = 123
    }
}

Altought if you always need only the second element: Altought 如果你总是只需要第二个元素:

The Split method is not always the best way to break a delimited string into substrings. Split 方法并不总是将分隔字符串拆分为子字符串的最佳方法。 If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method.如果您不想提取定界字符串的所有子字符串,或者如果您想要基于模式而不是一组定界字符来解析字符串,请考虑使用正则表达式,或结合其中一种搜索方法使用 Substring 方法返回字符的索引。 For more information, see Extract substrings from a string.有关详细信息,请参阅从字符串中提取子字符串。

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

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