问题描述
我的输入是:
My input is :
string[] sinput= { "1||age--11||gender--Female|||||", "0||age--16||gender--Male|||||" };
我需要循环输出,例如
I need output in loop such as
string soutput = ("age--11,age--16" );
string soutput = ("gender--Female,gender--Male" );
但是我已经尽力了,我无法实现此解决方案.
But I have tried myself, I couldn''t achieve this solution.
private void button8_Click(object sender, EventArgs e)
{
string[] ss = { "1||age--11||gender--Female|||||", "0||age--16||gender--Male|||||" };
for (int i = 0; i < ss.Length; i++)
{
string sss = ss[i].ToString().Replace("||",",").Replace(",,","");
}
}
我尝试过的事情:
What I have tried:
private void button8_Click(object sender, EventArgs e)
{
string[] ss = { "1||age--11||gender--Female|||||", "0||age--16||gender--Male|||||" };
for (int i = 0; i < ss.Length; i++)
{
string sss = ss[i].ToString().Replace("||",",").Replace(",,","");
}
}
推荐答案
string sss;
string[] ss = { "1||age--11||gender--Female|||||", "0||age--16||gender--Male|||||" };
string op1 = String.Empty;
string op2 = String.Empty;
for (int i = 0; i < ss.Length; i++)
{
sss = ss[i].ToString().Replace("||",",").Replace(",,","");
string[] p = sss.Split('','');
op1 += String.Format("{0},", p[1]);//age details
op2 += String.Format("{0},", p[2]);//gentder details
}
ss[0] = "1||age--11||gender--Female|||||";
ss[1] = "0||age--16||gender--Male|||||" ;
您可以在垂直条|
上Split
数组上的每个条目.如果确定数组中的每个项目都采用相同的格式,则可以使用StringSplitOptions.RemoveEmptyEntries
选项.
如果要从这些项目中重建字符串,则应使用 [ ^ ]类
下面的代码假定数组ss
中的每个项目与问题中显示的格式完全相同.
You can Split
each entry on the array on the vertical bar |
. If you are sure that every item in the array will be in that same format then you could use the StringSplitOptions.RemoveEmptyEntries
option.
If you are going to reconstruct a string from these items then you should use the StringBuilder[^] class
The code below assumes that each of the items in the array ss
is in exactly the same format as shown in your question
string[] ss = { "1||age--11||gender--Female|||||", "0||age--16||gender--Male|||||" };
StringBuilder sb1 = new StringBuilder("(");
StringBuilder sb2 = new StringBuilder("(");
for (int i = 0; i < ss.Length; i++)
{
var s1 = ss[i].Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries);
sb1.Append(s1[1]);
if(i < ss.Length - 1) sb1.Append(",");
sb2.Append(s1[2]);
if (i < ss.Length - 1) sb2.Append(",");
}
sb1.Append(")");
sb2.Append(")");
Debug.Print(sb1.ToString());
Debug.Print(sb2.ToString());
或者,您可以搜索以"age","gender"开头的项目-例如:
Alternatively you can search for the item that begins with "age", "gender" - example:
foreach (var s in s1.Where(s => s.StartsWith("age")))
{
sb1.Append(s);
if (i < ss.Length - 1) sb1.Append(",");
}
这篇关于拆分字符串数组并作为字符串返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!