如何将ID进行子串运算
本文关键字:子串 运算 ID | 更新日期: 2023-09-27 18:29:30
我得到了一个ID
分别为LSHOE-UCT。我如何将这些ID
进行子串和分离以成为:
gender = "L"
Product = "Shoe"
Category = "UCT"
这是我的代码:
private void assignProductCategory(string AcStockCategoryID)
{
//What should I insert?
string[] splitParameter = AcStockCategoryID.Split('-');
}
我需要将它们分离,识别它们,并从我的数据库中插入差异表。这就是我遇到的主要问题
string[] s = AcStockCategoryID.Split('-');
string gender = s[0].Substring(0, 1);
string Product= s[0].Substring(1, s[0].Length - 1);
string Category = s[1];
要尝试不同的方法,这也是可行的。
string id = "LSHOE-UCT";
string gender = id.Substring(0,1);
int indexOfDash = id.IndexOf("-");
string product = id.Substring(1, indexOfDash - 1);
string category = id.Substring(indexOfDash + 1);
试试这个,我只是随便打了一下,如果有错别字,我很抱歉。。。
string id = "LSHOE-UCT";
string[] arr = id.Split('-');
string gender = id.Substring(0,1); // this will give you L
string product = arr[0].Substring(1); // this will give you shoe
string category = arr[1]; // this will give you UCT;
警告:完成过度杀伤
您也可以使用LINQ的扩展方法(IEnumerable
)来实现这一点。我想我会做一个关于如何使用IEnumerable
来过度设计解决方案的思考实验:
int indexOfDash = id.IndexOf("-");
var firstPart = id.TakeWhile(s => s != '-');
var linqGender = firstPart.Take(1).ToArray()[0]; // string is L
var linqProduct = String.Join("", firstPart.Skip(1).Take(indexOfDash-1)); // string is SHOE
var secondPart = id.Skip(indexOfDash+1);
var linqCategory = String.Join("", secondPart); //string is UCT
编辑:由于ID格式在我的第一篇文章中不正确,所以更新了我的答案
如果你的acStockCategoryID
总是采用LSHOE-UTC
的格式,那么你可以做如下操作:
private void assignProductCategory(string AcStockCategoryID)
{
string[] splitParameter = AcStockCategoryID.Split('-');
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("gender=" + splitParameter[0].Substring(0, 1));
sb.AppendLine("Product=" + splitParameter[0].Substring(1));
sb.AppendLine("Category=" + splitParameter[1]);
// use sb.ToString() wherever you need the results
}
我会向后做。
public class LCU
{
public string Gender {get; set;}
public string Product {get; set;}
public string Category {get; set;}
public LCU(){}
}
private static LSU LShoe_UctHandler(string id)
{
var lcu = new LCU();
var s = id.Split('-');
if (s.length < 2) throw new ArgumentException("id");
lcu.Category = s[1];
lcu.Gender = s[0].Substring(0,1);
lcu.Product = s[0].Substring(1);
return lcu;
}
然后只需像这样将ID传递给LShoe_CutHandler…
var lcu = LShoe_UctHandler("LGlobtrotters-TrainingShoes");
Console.WriteLine("gender = {0}", lcu.Gender);
Console.WriteLine("Product = {0}", lcu.Product );
Console.WriteLine("Category = {0}", lcu.Category );
[手写-很抱歉输入错误和大小写错误]
试试这个:
string id = "LSHOE-UCT";
Console.WriteLine("Gender: {0}",id.Substring(0,1));
Console.WriteLine("Product: {0}",id.Split('-')[0].Substring(1));
Console.WriteLine("Product: {0}", id.Split('-')[1]);