简体   繁体   中英

Extract data from a big string

First of all, i'm using the function below to read data from a pdf file.

public string ReadPdfFile(string fileName)
    {
        StringBuilder text = new StringBuilder();

        if (File.Exists(fileName))
        {
            PdfReader pdfReader = new PdfReader(fileName);

            for (int page = 1; page <= pdfReader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                text.Append(currentText);
                pdfReader.Close();
            }
        }
        return text.ToString();
    }

As you can see , all data is saved in a string. The string looks like this:

label1: data1;
label2: data2;
label3: data3;
.............
labeln: datan;

My question: How can i get the data from string based on labels ? I've tried this , but i'm getting stuck:

   if ( string.Contains("label1")) 
   {
       extracted_data1 = string.Substring(string.IndexOf(':') , string.IndexOf(';') - string.IndexOf(':') - 1);
   }
   if ( string.Contains("label2"))
   {
       extracted_data2 = string.Substring(string.IndexOf("label2") + string.IndexOf(':') , string.IndexOf(';') - string.IndexOf(':') - 1); 
   } 

Have a look at the String.Split() function , it tokenises a string based on an array of characters supplied.

eg

 string[] lines = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);

now loop through that array and split each one again

foreach(string line in lines) {
      string[] pair = line.Split(new[] {':'});
      string key = pair[0].Trim();
      string val = pair[1].Trim();
      ....
   }

Obviously check for empty lines, and use .Trim() where needed...

[EDIT] Or alternatively as a nice Linq statement...

var result = from line in text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
             let  tokens = line.Split(new[] {':'})
             select tokens;

Dictionary<string, string> = 
       result.ToDictionary (key => key[0].Trim(), value => value[1].Trim());

It's pretty hard-coded, but you could use something like this (with a little bit of trimming to your needs):

    string input = "label1: data1;" // Example of your input
    string data = input.Split(':')[1].Replace(";","").Trim();

You can do this by using Dictionary<string,string> ,

            Dictionary<string, string> dicLabelData = new Dictionary<string, string>();
            List<string> listStrSplit = new List<string>();
            listStrSplit = strBig.Split(';').ToList<string>();//strBig is big string which you want to parse

            foreach (string strSplit in listStrSplit)
            {
                if (strSplit.Split(':').ToList<string>().Count > 1)
                {
                    List<string> listLable = new List<string>();
                    listLable = strSplit.Split(':').ToList<string>();

                    dicLabelData.Add(listLable[0],listLable[1]);//Key=Label,Value=Data
                }
            }

dicLabelData contains data of all label....

i think you can use regex to solve this problem. Just split the string on the break line and use a regex to get the right number.

You can use a regex to do it:

Regex rx = new Regex("label([0-9]+): ([^;]*);");
var matches = rx.Matches("label1: a string; label2: another string; label100: a third string;");

foreach (Match match in matches) {
    var id = match.Groups[1].ToString();
    var data = match.Groups[2].ToString();
    var idAsNumber = int.Parse(id);

    // Here you use an array or a dictionary to save id/data
}

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