3

I want to extract only those words between two commas. So, if the string is Ab Java, DE, 78801 The answer must be DE I have tried this code but it is not working

string search = "Ab  Java, DE, 78801 ";
int index = search.IndexOf(",");
string result = search.Substring(search.IndexOf(",") ,index);
MessageBox.Show(result);
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
Hisham shahid
  • 133
  • 1
  • 9

7 Answers7

6

If your string has always 2 commas, you can use String.Split for it like;

string search = "Ab  Java, DE, 78801 ";
Console.WriteLine(search.Split(',')[1]); // DE

Remember, this will you generate DE with an extra white space before it.

enter image description here

If you don't want that white space, you can use TrimStart() to remove it.

Console.WriteLine(search.Split(',')[1].TrimStart()); //DE
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

Your start and end in your Substring resolve to the same value.

Try using split and getting the second item, of course this assumes that your input always follows the pattern in your example. Otherwise you'll need to do something more complicated.

string[] searchItems = search.Split(',');
string result = searchItems[1].Trim(); // will output DE
Steve
  • 9,335
  • 10
  • 49
  • 81
1

try this

string[] splitedStr=search.Split(',');
string NewStr=splitedStr[1].ToString();
Dgan
  • 10,077
  • 1
  • 29
  • 51
0

Assuming your string always has just two commas, then:

search.Split(", ")[1]

will give you the desired text.

David Arno
  • 42,717
  • 16
  • 86
  • 131
0

Try this...

String str = "Ab  Java, DE, 78801 ";
String[] myStrings = str.split(",");
String marco = myStrings[1];
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
0

Try This. It May work...

string[] arrayStr = search.Split(',');
int len = arrayStr.Length;
for(int i =1;i<=len-2;i++)
{
   MessageBox.Show(result);
}
Sadequzzaman Monoj
  • 121
  • 2
  • 3
  • 10
0

That is something I would have solved using regular expressions. It might be slower than the String.Split solutions but it is way easier to read - in particular if the pattern is going to evolve over time.

The solution would than look like this:

string search = "Ab  Java, DE, 78801 ";
Regex r = new Regex(", *(.*?) *,", RegexOptions.Compiled);
Console.WriteLine(r.Match(search).Groups[1].ToString());

This writes DE without surrounding spaces. The regex instance should be a static member of your class, since I assume this is happening within a loop ...

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Markus
  • 3,225
  • 6
  • 35
  • 47