簡體   English   中英

如果找到匹配項,如何將字符串保存在數組中並顯示下一個字符串數組?

[英]How to save the strings in array and display the next string array if match found?

我從c#中讀取* .txt文件,並顯示在控制台中。

我的文本文件看起來像一張桌子。

diwas      hey
ivonne     how
pokhara    d kd
lekhanath  when
dipisha    dalli hos
dfsa       sasf

現在,我要搜索字符串“ pokhara”,如果找到它,則應顯示“ d kd”,如果找不到,則顯示“未找到”

我嘗試了什么?

string[] lines = System.IO.ReadAllLines(@"C:\readme.txt");
foreach(string line in lines)
{
    string [] words = line.Split();
    foreach(string word in words)
    {
        if (word=="pokhara")
        {
            Console.WriteLine("Match Found");
        }
    }
}

我的問題:找到匹配項,但如何顯示該行的下一個單詞。 另外有時在第二行中,有些單詞會以空格分隔成兩部分,我需要同時顯示兩個單詞。

我猜你的分隔符是制表符,然后可以使用String.Split和LINQ:

var lineFields = System.IO.File.ReadLines(@"C:\readme.txt")
    .Select(l => l.Split('\t'));
var matches = lineFields
    .Where(arr => arr.First().Trim() == "pokhara")
    .Select(arr => arr.Last().Trim());
// if you just want the first match:
string result = matches.FirstOrDefault();  // is null if not found

如果您不知道注釋所建議的分隔符,則表示有問題。 如果您甚至不了解如何分隔字段的規則,則很可能您的代碼不正確。 因此,首先確定業務邏輯,然后詢問創建文本文件的人員。 然后在String.Split使用正確的定界符。

如果是空格,則可以使用包含空格,制表符和string.Split() (不帶參數),也可以使用string.Split()包含空格的string.Split(' ') 但是請注意,如果字段也可以包含空格,則這是一個錯誤的分隔符。 然后,要么使用其他字段,要么使用引號將字符括起來,例如"text with spaces" 但是,然后我建議使用像Microsoft.VisualBasic.FileIO.TextFieldParser這樣的真實文本解析器,也可以在C#中使用它。 它具有HasFieldsEnclosedInQuotes屬性。

這有效...

  string[] lines = System.IO.ReadAllLines(@"C:\readme.txt");
    string stringTobeDisplayed = string.Empty;
    foreach(string line in lines)
    {
        stringTobeDisplayed = string.Empty;
        string [] words = line.Split();
         //I assume that the first word in every line is the key word to be found
          if (word[0].Trim()=="pokhara")
            {
                Console.WriteLine("Match Found");

                for(int i=1 ; i < words.Length ; i++)
                 {
                     stringTobeDisplayed += words[i]
                 }

                 Console.WriteLine(stringTobeDisplayed);

            }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM