这是示例代码。
我的字符串包含行星名称,顺序和颜色,由spaces
和NewLines
分隔。
我不想修改字符串来改变结果。
我想从字符串中创建3个列表,Order
,Name
和Color
。
| Order | Name | Color |
|------------|------------|------------|
| First | Mercury | Gray |
| Second | Venus | Yellow |
| Third | Earth | Blue |
| Fourth | Mars | Red |
这将从List
创建string
,由NewLine
分割。
string planets = "First Mercury Gray"
+ Environment.NewLine
+ "Second Venus Yellow"
+ Environment.NewLine
+ "Third Earth Blue"
+ Environment.NewLine
+ "Fourth Mars Red"
+ Environment.NewLine;
List<string> PlanetOrder = planets.Split(
new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
List<string> PlanetName = planets.Split(
new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
List<string> PlanetColor = planets.Split(
new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
但在每一行中,如何按space
拆分并选择单词[1]
订单,[2]
名称,[3]
颜色?
planets.Split(' ')[2]; //Name
答案 0 :(得分:6)
您可以执行以下操作。首先按$servername = "localhost";
$dbName = XXXXXXXXX
$dbUser = XXXXXXXXX;
$dbPass = XXXXXXXXX;
$conn = new PDO("mysql:host=$servername;dbname=XXXXXXXXX", $dbUser,
$dbPass);
$delimiter = "**";
$query = "SELECT * FROM `images` WHERE `portfolio_id` = 'X' AND `image_status` = 'X' ORDER BY rand()";
$conn->query($query);
while($row = mysql_fetch_array($query)){
$sVal = substr($row['image_full'],0);
$nString = $nString.$delimiter.$sVal;
}
拆分字符串,然后将结果的每一行拆分为Environment.NewLine
,并将项目添加到不同的列表中。
space
答案 1 :(得分:2)
LINQ方法:
public enum PlanetColumn
{
Order = 0,
Name = 1,
Color = 2
}
string planets = "First Mercury Gray"
+ Environment.NewLine
+ "Second Venus Yellow"
+ Environment.NewLine
+ "Third Earth Blue"
+ Environment.NewLine
+ "Fourth Mars Red"
+ Environment.NewLine;
var lookup = planets
.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(p => p.Trim().Split(' ').Select((value, colIndex) => new { Column = (PlanetColumn) colIndex, Value = value} ))
.ToLookup(prop => prop.Column, prop => prop.Value);
var planetOrders = lookup[PlanetColumn.Order].ToList();
var planetNames = lookup[PlanetColumn.Name].ToList();
var planetColors = lookup[PlanetColumn.Color].ToList();
注意:我添加enum
声明只是因为它看起来更干净,您可以直接使用整数值(并使用lookup[0]
,lookup[1]
,和lookup[2]
)
答案 2 :(得分:1)
或与Linq foreach:
List<string> planetOrder = new List<string>();
List<string> planetName = new List<string>();
List<string> planetColor = new List<string>();
planets.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(p =>
{
planetOrder.Add(p.Split(new[] { ' ' })[0]);
planetName.Add(p.Split(new[] { ' ' })[1]);
planetColor.Add(p.Split(new[] { ' ' })[2]);
});