Separating Comma-Separated Strings - c#

I have a string containing the value "12,13"
I want 2 strings from this string i.e
s1 = 12 and
s2 = 13
how can I separate in asp.net C#?
I have not much time to google it that's why I am posting it here.
Hope anyone can answer this.
Thanks in advance

Try this:
string firstString = "12,13";
string[] values = firstString.Split(',');
string s1 = values[0];
string s2 = values[1];

string numbersText ="12,13"
string[] numbers= numbersText.Split(',');
if(numbers.Length >= 2) // check length of array if you not sure about text before access items of it
{
string s1 =numbers[0];
string s1 =numbers[1];
}

You can use string.Split() method
example:
string text = "12,13";
string[] parts = text.Split(',');
string s1 = parts[0]; // "12"
string s2 = parts[1]; // "13"

Related

Retrieving string from a string which is in between two String?

i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want

How to split a string and store in different string array

if i have a string like
string hello="HelloworldHellofriendsHelloPeople";
i would like to store this in a string like this
Helloworld
Hellofriends
HelloPeople
It has to change the line when it finds the string "hello"
thanks
string hello = "HelloworldHellofriendsHelloPeople";
var a = hello.Split(new string[] { "Hello"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in a)
Console.WriteLine("Hello" + s);
var result = hello.Split(new[] { "Hello" },
StringSplitOptions.RemoveEmptyEntries)
.Select(s => "Hello" + s);
You can use this regex
(?=Hello)
and then split the string using regex's split method!
Your code would be:
String matchpattern = #"(?=Hello)";
Regex re = new Regex(matchpattern);
String[] splitarray = re.Split(sourcestring);
You can use this code - based on string.Replace
var replace = hello.Replace( "Hello", "-Hello" );
var result = replace.Split("-");
You could use string.split to split on the word "Hello", and then append "Hello" back onto the string.
string[] helloArray = string.split("Hello");
foreach(string hello in helloArray)
{
hello = "Hello" + hello;
}
That will give the output you want of
Helloworld
Hellofriends
HelloPeople

How to search for a pattern within a string?

I have a string which contains the following output
login;windows
db;sql
audit;failure
how do I check if this string contains the word "audit;failure"?
I have use the following code but was not successful:
currLine = sr.ReadToEnd();
string[] splited = Regex.Split(currLine, "~~~~~~~~~~~~~~");
case1 = splited[0];
string case1 = "";
string pattern1 = "audit;failure";
if (Regex.IsMatch(case1, pattern1)){
console.writeline("success"!);
}
I must search through the variable case1 and not the string currLine
thaks in advance! :D
Also make sure that you remove the line string case1 = "";
if(case1.Contains("audit;failure"))
console.writeline("success"!);
I think you just need to adjust case1 string ........
string case1 = "";
currLine = sr.ReadToEnd();
string[] splited = Regex.Split(currLine, "~~~~~~~~~~~~~~");
case1 = splited[0];
string pattern1 = "audit;failure";
if (Regex.IsMatch(case1, pattern1)){
console.writeline("success"!);
}
Simply use String.Contains(), use a code like follows
if(sr.Contains("audit;failure")
{
}
One way to do it would be to split this first into the lines.
string[] lines = sr.split (new string[]{ Environment.LineBreak});
foreach(string line in lines){
string[] parts = line.split(new char[] {';'});
if(parts[0] == "audit")
return parts[1];
}
return "not set";
This will return whatever stands behind "audit" and is easily adaptable to return whatever you need. The final return will be triggered if no audit-line was present.

How to split string using Substring

I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?
Try this:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
or
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
to split, the latter will remove the empty string.
Adding .Last() will get you the last item.
e.g.
toSplit.Split('/').Last();
Use .Split().
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
This site have quite a few examples of splitting strings in C#. It's worth a read.
Using .Split and a little bit of LINQ, you could do the following
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
Otherwise you could do
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts
string[] arr = string1.split('/');
string result = arr[arr.length - 1];
string [] split = words.Split('/');
This will give you an array split that will contain "", "Test1" and "Test2".
If you just want the Test2 portion, try this:
string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1); //This will grab the second element.
string inputString = "/Test1/Test2";
string[] stringSeparators = new string[] { "/Test1/"};
string[] result;
result = inputString.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write("{0}",s);
}
OUTPUT : Test2

How do I split a string into an array?

I want to split a string into an array. The string is as follows:
:hello:mr.zoghal:
I would like to split it as follows:
hello mr.zoghal
I tried ...
string[] split = string.Split(new Char[] {':'});
and now I want to have:
string something = hello ;
string something1 = mr.zoghal;
How can I accomplish this?
String myString = ":hello:mr.zoghal:";
string[] split = myString.Split(':');
string newString = string.Empty;
foreach(String s in split) {
newString += "something = " + s + "; ";
}
Your output would be:
something = hello; something = mr.zoghal;
For your original request:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
var somethings = split.Select(s => String.Format("something = {0};", s));
Console.WriteLine(String.Join("\n", somethings.ToArray()));
This will produce
something = hello;
something = mr.zoghal;
in accordance to your request.
Also, the line
string[] split = string.Split(new Char[] {':'});
is not legal C#. String.Split is an instance-level method whereas your current code is either trying to invoke Split on an instance named string (not legal as "string" is a reserved keyword) or is trying to invoke a static method named Split on the class String (there is no such method).
Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
string something = split[0];
string something1 = split[1];
Now you will have
something == "hello"
and
something1 == "mr.zoghal"
both evaluate as true. Is this what you are looking for?
It is much easier than that. There is already an option.
string mystring = ":hello:mr.zoghal:";
string[] split = mystring.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);

Categories

Resources