将两个字符串拆分为父级和子级? [英] Split two strings into parent and child ?

查看:76
本文介绍了将两个字符串拆分为父级和子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库parent / child,parent / parent2 / parent3 / child,parent / parent2 / parent3 / parent4等获取以下字符串。姓名(父母/子女)各不相同,可以是任何东西。



父母/子女

父母/ < b> parent2 / child

parent / parent2 / parent3 / child

parent / parent2 / parent3 / parent4 /孩子



这个父母和孩子与/相关。字符串在/之前是父级,在/之后是子级。我需要动态分割这个字符串并分别将它们输入到父和子的两个数组中,以便我可以知道谁是哪个孩子的父亲。



到目前为止,我有这段代码,我坚持逻辑。

Hi, I am getting the following strings from the database "parent/child", "parent/parent2/parent3/child" , "parent/parent2/parent3/parent4" and so on. The names (parent/child) vary and can be anything.

parent/child
parent/parent2/child
parent/parent2/parent3/child
parent/parent2/parent3/parent4/child

This parent and child are related with a "/". The string comes before "/" is parent and which comes after the "/" is a child. I need to split this string dynamically and enter them into two arrays for parent and child respectively so that I can know who is the father of which child.

So far I have this code, I am stuck with the logic.

foreach(string str in data.strs)
{
if(str.contains("/")
{
string[] names=str.Split('/');
foreach(string name in names)
{
//todo
}
}
}

推荐答案

您正在尝试配对父项及其子项,我认为使用List包含一对键值 [< a href =http://www.dotnetperls.c om / keyvaluepairtarget =_ blanktitle =New Window> ^ ]更适合捕捉这种关系。看看这个例子:

You are trying to pair up parent and its child, I think using List to contain pairs of key value[^] would be more suitable to capture this relationship. Check out this example:
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string str = "parent/parent2/parent3/parent4/child";
        if(str.Contains("/")){
            string[] persons = str.Split('/');

            var kinship = new List<KeyValuePair<string, string>>();

            for(int i=0; i < persons.Length; i++){

                string parent = persons[i];

                string child = i < persons.Length-1? persons[i+1]: "nil";

                kinship.Add(new KeyValuePair<string, string>(parent, child));

                Console.WriteLine("parent: {0}, child: {1}\n", parent, child);
            }
        }
    }
}


这篇关于将两个字符串拆分为父级和子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆