开发者

cutting from string in C#

开发者 https://www.devze.com 2023-01-31 20:39 出处:网络
My strings look like that:aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don\'t have the same length. I tried to use Substring(), but what about

My strings look like that: aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don't have the same length. I tried to use Substring(), but what about / ?

I want to add 'aaa' to the first treeNode, 'b' to the second etc. I know how to add something 开发者_如何转开发to treeview, but i don't know how can i receive this parts.


Maybe the Split() method is what you're after?

string value = "aaa/b/cc/dd/ee";

string[] collection = value.Split('/');

Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.

Based on your updates related to a TreeView (ASP.Net? WinForms?) you can do this:

foreach(string text in collection)
{
    TreeNode node = new TreeNode(text);
    myTreeView.Nodes.Add(node);
}


Use Substring and IndexOf to find the location of the first /

To get the first part:

// from memory, need to test :)
string output = String.Substring(inputString, 0, inputString.IndexOf("/")); 

To just cut the first part:

// from memory, need to test :)
string output = String.Substring(inputString, 
                                 inputString.IndexOf("/"),     
                                 inputString.Length - inputString.IndexOf("/"); 


You would probably want to do:

string[] parts = "aaa/b/cc/dd/ee".Split(new char[] { '/' });


Sounds like this is a job for... Regular Expressions!


One way to do it is by using string.Split to split your string into an array, and then string.Join to make whatever parts of the array you want into a new string.

For example:

var parts = input.Split('/');
var processedInput = string.Join("/", parts.Skip(1));

This is a general approach. If you only need to do very specific processing, you can be more efficient with string.IndexOf, for example:

var processedInput = input.Substring(input.IndexOf('/') + 1);
0

精彩评论

暂无评论...
验证码 换一张
取 消