Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a string like 'X:Y,A:B,C:D,M:N', how do I get a substring 'X,Y,C,M' from this? Need to always pick the first substring before :

What I have tried:

I tried to split the string using ',' and then use IndexOf to get the substring before : using a foreach loop but not able to concatenate the string back to X,A,C,M
Posted
Updated 5-Apr-23 15:26pm
v2
Comments
PIEBALDconsult 5-Apr-23 20:57pm    
I would use a Regular Expression.
diadtp 5-Apr-23 21:06pm    
can you give an example?

Something like this:

C#
System.Text.RegularExpressions.MatchCollection mat = 
System.Text.RegularExpressions.Regex.Matches 
( 
  @"X:Y,A:B,C:D,M:N" 
,
  @"(\w+?):"
,
  System.Text.RegularExpressions.RegexOptions.Compiled
) ;

System.Text.StringBuilder sb = new System.Text.StringBuilder() ;

for ( int i = 0 ; i < mat.Count ; i++ )
{
  sb.AppendFormat ( "{0}," , mat [ i ].Groups [ 1 ].Value ) ;
}

sb.Length-- ;

string res = sb.ToString() ;
 
Share this answer
 
Here are another two ways:
C#
string text = "X:Y,A:B,C:D,M:N";

string[] parts = text.Split(',');

// This
string[] identifiers1 = parts
    .Select(part => part.Substring(0, 1))
    .ToArray();

Console.WriteLine(string.Join(", ", identifiers1));

// or this

string[] identifiers2 = new string[parts.Length];

for (int i = 0; i < parts.Length; i++)
{
    identifiers2[i] = parts [i].Substring(0,1);
}

Console.WriteLine(string.Join(", ", identifiers2));

Outputs:
X, A, C, M
X, A, C, M
 
Share this answer
 
v2
Comments
diadtp 5-Apr-23 22:37pm    
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900