简体   繁体   中英

c# search a text using c# but the answer is next to the keyword

i have a string and i need to search.

for example i need to search the "Exif Byte Order" keyword and the output is the whole word next to it

Little-endian

how can i do this? i tried searching but the solutions but i can't find a problem similar to mine.

this is the string

File    File Name   NHD-and-Chronicling-America_04.jpg
File    Directory   C:/Users/Desktop/images
File    File Size   65 kB
File    File Modification Date/Time 2016:08:04 14:16:37-07:00
File    File Access Date/Time   2016:08:10 13:38:40-07:00
File    File Creation Date/Time 2016:08:10 13:38:40-07:00
File    File Permissions    rw-rw-rw-
File    File Type   JPEG
File    File Type Extension jpg
File    MIME Type   image/jpeg
File    Exif Byte Order Little-endian (Intel, II)
File    Image Width 274
File    Image Height    498
File    Encoding Process    Baseline DCT, Huffman coding
File    Bits Per Sample 8
File    Color Components    3

I suggest using Linq :

  string source = ...

  string key = "Exif Byte Order";  

  var result = source
    .Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
    .Select(line => {
       int index = line.IndexOf(key, StringComparison.OrdinalIgnoreCase);

       return index < 0 ? null : line.Substring(index + key.Length).Trim();
     })
    .FirstOrDefault(line => line != null);

  // Little - endian(Intel, II)
  Console.Write(result);

If you want to obtain Little-endian exactly, you can try regular expressions instead of simple line.IndexOf :

 var result = source
   .Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries )
   .Select(line => Regex.Match(line, "(?<=" + Regex.Escape(key) + @"\s*)([\w\s-/]+)"))
   .FirstOrDefault(match => match.Success)
  ?.Value
  ?.Trim();

Split() your string by search string. You'll get a string that starts with what you want. Split that too by a space or whatever you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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