How can I separate www.myurl.com/help,mycustomers into www.myurl.com/help and mycustomers and put them in different string variables?
try this:
string MyString="www.myurl.com/help,mycustomers";
string first=MyString.Split(',')[0];
string second=MyString.Split(',')[1];
If MyString contains multiple parts, you can use:
string[] CS = MyString.Split(',');
And each parts can be accessed like:
CS[0],CS[1],CS[2]
For example:
string MyString="www.myurl.com/help,mycustomers,mysuppliers";
string[] CS = MyString.Split(',');
CS[0];//www.myurl.com/help
CS[1];//mycustomers
CS[2];//mysuppliers
If you want to know more about Split function. Read this.
it can be a comma or a hash
Then you can use String.Split(Char[]) method like;
string s = "www.myurl.com/help,mycustomers";
string first = s.Split(new []{',', '#'},
StringSplitOptions.RemoveEmptyEntries)[0];
string second = s.Split(new [] { ',', '#' },
StringSplitOptions.RemoveEmptyEntries)[1];
As Steve pointed, using indexer might not be good because your string couldn't have any , or #.
You can use for loop also like;
string s = "www.myurl.com/help,mycustomers";
var array = s.Split(new []{',', '#'},
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(string.Format("{0}: {1}", i, array[i]));
}
You can have a short and sweet solution to this as :
string[] myArray= "www.myurl.com/help,mycustomers".Split(',');
Related
How do I split the string into a string array.
My string looks like this
string orgString = "1234-|#$#|-George,Michael -$#%#$-65489-|#$#|-Lawrence, Steve J -$#%#$-7897954-|#$#|-Oliver Mike -$#%#$-56465-|#$#|-Waldimir Tursoky";
Now I want my string array to store name and number along with -|#$#|-
I tried the following code
string[] strArray = orgString.Split(new string[] {"-$#%#$-"}, StringSplitOptions.RemoveEmptyEntries);
My output looks like this:
"1234-|#$#|-George,Michael "
But my desired output is (name first, number last)
"George,Michael -|#$#|-1234"
How can i achieve this in C#?
Just swap parts in the resulting string :
string orgString = "1234-|#$#|-George,Michael -$#%#$-65489-|#$#|-Lawrence, Steve J -$#%#$-7897954-|#$#|-Oliver Mike -$#%#$-56465-|#$#|-Waldimir Tursoky";
string[] resultingList = orgString.Split(new string[] {"-$#%#$-"}, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Split(new string[] {"-|#$#|-"}, StringSplitOptions.RemoveEmptyEntries).Aggregate((x11,y)=>{return y+" -|#$#|- "+x11;})).ToArray();
foreach(string result in resultingList)
{
Console.WriteLine(result);
}
You can split again and then recombine
string outerDivider = "-$#%#$-";
string innerDivider = "-|#$#|-";
var results = orgString
// Split by outer divider
.Split(new string[] { outerDivider }, StringSplitOptions.RemoveEmptyEntries)
// Then for each of the results, split again on the inner divider
.Select(x => x.Split(new string[] { innerDivider }, StringSplitOptions.RemoveEmptyEntries))
// Swap the order of elements around the inner divider and recombine into a string
.Select(x => string.Join(innerDivider, x[1], x[0]));
I am trying to add a leaderboard in my unity app
I have a long string as below(just an example, actual string is http pipe data from my web service, not manually stored):
string str ="name1|10|junk data.....\n
name2|9|junk data.....\n
name3|8|junk data.....\n
name4|7|junk data....."
I want to get the first word (string before the first pipe '|' like name1,name2...) from every line and store it in an array and then get the numbers (10,9,8... arter the '|') and store it in an other one.
Anyone know whats the best way to do this?
Fiddle here: https://dotnetfiddle.net/utp4HK
code below, you may want to revisit the algorithm for performance, but if that is not an issue, this will do the trick;
using System;
public class Program
{
public static void Main()
{
string str ="name1|10|junk data.....\nname2|9|junk data.....\nname3|8|junkdata.....\nname4|7|junk data.....";
foreach (var line in str.Split('\n'))
{
Console.WriteLine(line.Split('|')[0]);
}
}
}
First split by new-line characters:
string[] lines = str.Split(new string[]{Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Then you can use LINQ to get both arrays:
var data = lines.Select(l => l.Trim().Split('|')).Where(arr => arr.Length > 1);
string[] names = data.Select(arr => arr[0].Trim()).ToArray();
string[] numbers = data.Select(arr => arr[1].Trim()).ToArray();
Check out this link on splitting strings: http://msdn.microsoft.com/en-us/library/ms228388.aspx
You could first create an array of strings (one for each line) by splitting the long string with \n as the delimeter.
Then, you could split each line with | as the delimeter. The name would be the 0th index of the array and the number would be the 1st index of the array.
First of all, you can't have a multi line string without using verbatim string literal. With using verbatim string literal, you can split your string based on \r\n or Environment.NewLine like;
string str = #"name1|10|junk data.....
name2|9|junk data.....
name3|8|junk data.....
name4|7|junk data.....";
var array = str.Split(new []{Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
Console.WriteLine(item.Split(new[]{"|"},
StringSplitOptions.RemoveEmptyEntries)[0].Trim());
}
Output will be;
name1
name2
name3
name4
Try this:
string str ="name1|10|junk data.....\n" +
"name2|9|junk data.....\n" +
"name3|8|junk data.....\n" +
"name4|7|junk data.....";
string[] tempArray1 = str.Split('\n');
string[] tempArray2 = null;
string[,] newArray = null;
for (int i = 0; i < tempArray1.Length; i++)
{
tempArray2 = tempArray1[i].Split('|');
if (newArray[0, 0].ToString().Length == 0)
{
newArray = new string[tempArray1.Length, tempArray2.Length];
}
for (int j = 0; j < tempArray2.Length; j++)
{
newArray[i,j] = tempArray2[j];
}
}
I have to write a program which parses a string for words starting with '#' and return the words along with the # symbol.
I have tried something like:
char[] delim = { '#' };
string[] strArr = commenttext.Split(delim);
return strArr;
But it returns all the words without '#' in an array.
I need something pretty straight forward.No LINQ like things
If the string is "abc #ert #xyz" then I should get back #ert and #xyz.
If you define "word" as "separated by spaces" then this would work:
string[] strArr = commenttext.Split(' ')
.Where(w => w.StartsWith("#"))
.ToArray();
If you need something more complex, a Regular Expression might be more appropriate.
I need something pretty straight forward.No LINQ like things>
The non-Linq equivalent would be:
var words = commenttext.Split(' ');
List<string> temp = new List<string>();
foreach(string w in words)
{
if(w.StartsWith("#"))
temp.Add(w);
}
string[] strArr = temp.ToArray();
If you're against using Linq, which you should not be unless you're required to use older .NET versions, an approach along these lines would suit your needs.
string[] words = commenttext.Split(delimiter);
for (int i = 0; i < words.Length; i++)
{
string word = words[i];
if (word.StartsWith(delimiter))
{
// save in array / list
}
}
const string test = "#Amir abcdef #Stack #C# mnop xyz";
var splited = test.Split(' ').Where(m => m.StartsWith("#")).ToList();
foreach (var b in splited)
{
Console.WriteLine(b.Substring(1, b.Length - 1));
}
Console.ReadKey();
Suppose i have a string separator eg "~#" and have a string like "leftSide~#righside"
How do you get you leftside and rightside without separator?
string myLeft=?;
string myRight=?
How do you do it?
thanks
string[] splitResults = myString.Split(new [] {"~#"}, StringSplitOptions.None);
And if you want to make sure you get at most 2 substrings (left and right), use:
int maxResults = 2;
string[] splitResults =
myString.Split(new [] {"~#"}, maxResults, StringSplitOptions.None)
string[] strs =
string.Split(new string[] { "~#" }, StringSplitOptions.RemoveEmptyEntries);
use String.Split
string str = "leftSide~#righside";
str.Split(new [] {"~#"}, StringSplitOptions.None);
the split function has an overload that accepts an array of strings instead of chars...
string s = "leftSide~#righside";
string[] ss = s.Split(new string[] {"~#"}, StringSplitOptions.None);
var s = "leftSide~#righside";
var split = s.Split (new string [] { "~#" }, StringSplitOptions.None);
var myLeft = split [0];
var myRight = split [1];
String myLeft = value.Substring(0, value.IndexOf(seperator));
String myRight = value.Substring(value.IndexOf(seperator) + 1);
strvalues=#"Emp_Name;Emp_ID;23;24;25;26";
contains values like this
taking the above string as an input the output should be like this
string strresult=#"23;24;25;26";
is there any built in function to do like this
thnaks
prince
Let's add a LINQ solution to the lot...
string result = String.Join(";", values.Split(';').Skip(2).ToArray());
Or another possibility
string result = values.Split(new char[] { ';' }, 3)[2];
Both work, but I wouldn't call them elegant either.
string[] values = strvalues.Split(new char[] { ';' });
values will be a string array containing the first column in values[0], second in values[1], etc.
You can use it like this:
for (int i = 2, i < values.Length, i++) {
Console.WriteLine(values[i]);
}
Regex class?
var strresult = new Regex("([0-9]+;?)*").Match(strvalues).Value;
string strresult = strvalues.Replace("Emp_Name;Emp_ID;", "");
How about...
string result = String.Join(";", strvalues.Split(';'), 2, 4);