简体   繁体   中英

Searching for a string in a string

Dear stackoverflow members,

I have this string:

 string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";

I want to search for the values where the "keyword" is Position. In this case I want to get back 1 and 2. Each value is "indexed" with its own "keyword". So the value 1 in this string has the Position seperator. The value 1234 has the Article seperator and the value 4321 has the Quantity seperator.

I need a way to search through the string and want to get all positions, articles and quantitys back. Without the keywords.

Output shout be:

 string[] position = {"1", "2"};
 string[] article = {"1234", "4323"};
 string[] quantity = {"4321", "3323"};

Hopefully some can help me here.

Thanks!

This is q quick solution I've come up with in LinqPad:

void Main()
{
        string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
        var Articles = Indices(data, "Article").Dump("Articles: ");
        var Posistions = Indices(data, "Position").Dump("Positions :");
        var Quantities = Indices(data, "Quantity").Dump("Quantities :");
}

// Define other methods and classes here
public List<int> Indices(string source, string keyword)
{
    var results = new List<int>();
    //source: http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number
    var temp = Regex.Split(source, "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)").ToList().Where (r => !String.IsNullOrEmpty(r)).ToList();
    //select the list with index only where key word matches
    var indices = temp.Select ((v,i) => new {index = i, value = v})
                      .Where (t => t.value == keyword);
    foreach (var element in indices)
    {
        int val;
        //get previous list entry based on index and parse it
        if(Int32.TryParse(temp[element.index -1], out val))
        {
            results.Add(val);
        }
    }
    return results;
}

Output: 在此处输入图片说明

Here's a possible algorithm:

  • Run trough the list and take each number / keyword.
  • Put them in a dictionary with key "keyword", value a list with all "numbers".
  • Iterate the dictionary and print they key + its values.

Below snippet can use to get the output like what you expected.

string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";

StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
bool isDigit = false;
bool isChar = false;
Dictionary<int, string> dic = new Dictionary<int, string>();
int index = 0;

for (int i = 0; i < data.Length; i++)
 {
  if (char.IsNumber(data[i]))
   {
     isDigit = true;
     if (isChar)
      {
         dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
         index++;
         isChar = false;
         sb.Remove(0, sb.Length);
         sbWord.Remove(0, sbWord.Length);
      }

     }
     else
            {
                isDigit = false;
                isChar = true;
                sbWord.Append(data[i]);
            }

            if (isDigit)
                sb.Append(data[i]);

            if (i == data.Length - 1)
            {
                dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
            }
        }

        List<string> Position = new List<string>();
        List<string> Article = new List<string>();
        List<string> Quantity = new List<string>();

        if (dic.Count > 0)
        {
            for (int i = 0; i < dic.Count; i++)
            {
                if (dic[i].Split('|')[1] == "Position")
                    Position.Add(dic[i].Split('|')[0]);


                else if (dic[i].Split('|')[1] == "Article")

                    Article.Add(dic[i].Split('|')[0]);

                else
                    Quantity.Add(dic[i].Split('|')[0]);
            }
        }

        string[] Position_array = Position.ToArray();
        string[] Article_array = Article.ToArray();
        string[] Quantity_array = Quantity.ToArray();

Try this simple solution.

class StrSplit{
  public static void main(String args[]){

   int i;
  String str = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
  String pattern=  "(?<=Position)|(?<=Article)|(?<=Quantity)";

  String[] parts = str.split(pattern);
  List<String> Position = new ArrayList<String>();
  List<String> Article = new ArrayList<String>();
  List<String> Quantity = new ArrayList<String>();

     for( i=0;i<parts.length;i++)
     {
          pattern="Position";
          String[] subParts;
          if(parts[i].contains(pattern))
          {
                 subParts = parts[i].split(pattern);
                 Position.add(subParts[0]);
          }
          pattern="Article";
          if(parts[i].contains(pattern))
          {
                   subParts = parts[i].split(pattern);
                   Article.add(subParts[0]);
          }
          pattern="Quantity";
          if(parts[i].contains(pattern))
          {
                  subParts = parts[i].split(pattern);
                  Quantity.add(subParts[0]);
          }

   }
   System.out.println("Position:");
   for(i = 0; i < Position.size(); i++) {
        System.out.println(Position.get(i));
    }
     System.out.println("Article:");
   for(i = 0; i < Article.size(); i++) {
        System.out.println(Article.get(i));
    }
     System.out.println("Quantity:");
 for(i = 0; i < Quantity.size(); i++) {
        System.out.println(Quantity.get(i));
    }
}
}

Output:
Position: 1 2 Article: 1234 4323 Quantity: 4321 3323

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