Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and get first value only

Tags:

c#

I wonder if it's possible to use split to devide a string with several parts that are separated with a comma, like this:

title, genre, director, actor 

I just want the first part, the title of each string and not the rest?

like image 589
3D-kreativ Avatar asked Jun 03 '12 07:06

3D-kreativ


People also ask

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you get the first value from a comma separated string in Python?

You can use the split() method. It returns an array String[] , so you can access to an element by using the syntax someArray[index] . Since you want to get the first elemnt, you can use [0] . String first_word = s.

How do you split the first part of a string in Python?

Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] .

Does split () alter the original string?

The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it. It doesn't make any modifications to the original string.


2 Answers

string valueStr = "title, genre, director, actor"; var vals = valueStr.Split(',')[0]; 

vals will give you the title

like image 89
bhupendra patel Avatar answered Sep 21 '22 15:09

bhupendra patel


Actually, there is a better way to do it than split:

public string GetFirstFromSplit(string input, char delimiter) {     var i = input.IndexOf(delimiter);      return i == -1 ? input : input.Substring(0, i); } 

And as extension methods:

public static string FirstFromSplit(this string source, char delimiter) {     var i = source.IndexOf(delimiter);      return i == -1 ? source : source.Substring(0, i); }  public static string FirstFromSplit(this string source, string delimiter) {     var i = source.IndexOf(delimiter);      return i == -1 ? source : source.Substring(0, i); } 

Usage:

string result = "hi, hello, sup".FirstFromSplit(','); Console.WriteLine(result); // "hi" 
like image 25
SimpleVar Avatar answered Sep 23 '22 15:09

SimpleVar