Click here to Skip to main content
15,893,968 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello i want to split my string and want to show only a single word in my program
suppose this is my string
C#
string value = "P 2016-10-17,P 2016-10-18,P 2016-10-19,P 2016-10-20,P 2016-10-21";

and after split them i have received (P 2016-10-17) for each in the string here i want to just display only P and want to hide date in the string

What I have tried:

C#
string value = "P 2016-10-17,P 2016-10-18,P 2016-10-19,P 2016-10-20,P 2016-10-21";
          char[] delimiters = new char[] { ',' };
          string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

i have use above code for split them the split is successfully done but i want to display on p from the string
Posted
Updated 20-Oct-16 21:01pm

There are two ways to do this.
The first is to split the string twice:
C#
string value = "P 2016-10-17,P 2016-10-18,P 2016-10-19,P 2016-10-20,P 2016-10-21";
string[] parts = value.Split(',');
foreach (string part in parts)
    {
    string[] subParts = part.Split(' ');
    if (subParts.Length > 0) Console.WriteLine(subParts[0]);
    }

The second is to use a regex:
C#
string value = "P 2016-10-17,P 2016-10-18,P 2016-10-19,P 2016-10-20,P 2016-10-21";
MatchCollection matches = Regex.Matches(value, @"(?<=^|,)(?<Prefix>.+?)(?=\s)");
foreach (Match m in matches)
    {
    Console.WriteLine(m.Value);
    }
The regex is a little more complex, but a lot more flexible!
 
Share this answer
 
Comments
AZHAR SAYYAD 21-Oct-16 7:40am    
string value = "P 2016-10-17,P 2016-10-18,P 2016-10-19,P 2016-10-20,P 2016-10-21";
MatchCollection matches = Regex.Matches(value, @"(?<=^|,)(?<prefix>.+?)(?=\s)");
foreach (Match m in matches)
{
Console.WriteLine(m.Value);
}

how to get the index of m.value
Make use of SubString and IndexOf as shown below.

string newString = parts[0].ToString().Substring(0, parts[0].ToString().Length - 11);

You can sort out the finer details.
 
Share this answer
 
v2
You can use Substring() to do that
Something like following should help-
C#
for(int i=0;i< parts.Length;i++)
      {              
              Console.WriteLine("{0}",parts[i].Substring(0, input.Length-11)); // 11 characters to exclude the date and one whitespace in between
              //you can create another array to store these values now
      }

Hope, it helps :)
 
Share this answer
 

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