我有一个像这样的字符串“4 Program Files(x86)2”。 4是行ID,2是父ID,文本之间是内容。 如何从给定的字符串中提取每个字符串,以便创建具有属性ID,内容和ParentID的对象?
答案 0 :(得分:3)
使用IndexOf/LastIndexOf
或Substring
等字符串方法:
int firstSpaceIndex = input.IndexOf(' ');
int lastSpaceIndex = input.LastIndexOf(' ');
// check that firstSpaceIndex != lastSpaceIndex and both are >= 0 because that would be invalid
string id = input.Remove(firstSpaceIndex);
string content = input.Substring(firstSpaceIndex + 1, lastSpaceIndex - firstSpaceIndex).Trim();
string parentId = input.Substring(lastSpaceIndex).Trim();
答案 1 :(得分:1)
你应该使用
String.ToCharArray方法()
示例:
string myString =new string();
char[] strChars=myString.ToCharArray();
char lineID=strChars[0];
char parentID=strChars[strChars.length-1];
char[] content=new char[strChars.length-2];
Buffer.BlockCopy(content,0,strChars,1,strchars.length-1);
string strContent =new string(content);
答案 2 :(得分:1)
使用String.Split()
,List<String>
和String.Join()
的另一种方法:
string data = "4 Program Files (x86) 2";
string LineID = "";
string ParentID = "";
string Content = "";
List<string> values = new List<string>(data.Split(' '));
if (values.Count >= 3)
{
LineID = values[0];
ParentID = values[values.Count - 1];
values.RemoveAt(0);
values.RemoveAt(values.Count - 1);
Content = String.Join(" ", values.ToArray());
}
Console.WriteLine("LineID = " + LineID);
Console.WriteLine("ParentID = " + ParentID);
Console.WriteLine("Content = " + Content);
答案 3 :(得分:0)
您可以使用正则表达式。在你的情况下,它将是这样的:
string regex = "(?![0-9])(.*)(?=[0-9])";
string toSplit = "4 Program Files (x86) 2";
string [] result = Regex.Split(toSplit, regex);
foreach (string s in result)
{
Console.Out.WriteLine(s);
}
Console.ReadLine();
数组中的第二个字符串是您的结果。参考System.Text.RegularExpressions;在你班上。
答案 4 :(得分:0)
此解决方案使用Substring(),但它假设您知道hand_id和line_ID的长度(在下面的代码中为1)...
string mystr = "4 Program Files (x86) 2";
mystr = mystr.Substring(1, mystr.Length - 2);
Console.WriteLine(mystr);// Program Files (x86)
mystr = "4 Program Files (x86) 2";
mystr = mystr.Substring(0, 1);
Console.WriteLine(mystr);//print 4
mystr = "4 Program Files (x86) 2";
mystr = mystr.Substring( mystr.Length-1, 1);
Console.WriteLine(mystr);//print 2
答案 5 :(得分:0)
这应该有效
var str = "4 Program Files (x86) 2";
var splitted = str.Split(' '); // splits the string
var id = splitted[0]; // the first position of the array is the id
var parentId = splitted[splitted.Length - 1]; // the last position of the array is the parentId
var content = str.Substring(id.Length, str.Length - id.Length - parentId.Length); // gets the content between the id and parentId