Split a string into String Array in c# - c#

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]));

Related

Fetch Occurrence of alphabet in a string c#

I have a string which look likes
E-1,E-2,F-3,F-1,G-1,E-2,F-5
Now i want output in array like
E, F, G
I only want the name of character once that appears in the string.
My Code Sample is as follows
string str1 = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] newtmpSTR = str1.Split(new char[] { ',' });
Dictionary<string, string> tmpDict = new Dictionary<string, string>();
foreach(string str in newtmpSTR){
string[] tmpCharPart = str.Split('-');
if(!tmpDict.ContainsKey(tmpCharPart[0])){
tmpDict.Add(tmpCharPart[0], "");
}
}
Is there any easy way to do it in c#, using string function, If yes the how
string input = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] splitted = input.Split(new char[] { ',' });
var letters = splitted.Select(s => s.Substring(0, 1)).Distinct().ToList();
Maybe you can obtain the same result with a regular expression! :-)

Get first word on every new line in a long string?

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];
}
}

Separating two strings if any character is encountered

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(',');

Splitting by string with a separator with more than one char

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);

How do I split a string by a multi-character delimiter in C#?

What if I want to split a string using a delimiter that is a word?
For example, This is a sentence.
I want to split on is and get This and a sentence.
In Java, I can send in a string as a delimiter, but how do I accomplish this in C#?
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
Example from the docs:
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ...
result = source.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
You can use the Regex.Split method, something like this:
Regex regex = new Regex(#"\bis\b");
string[] substrings = regex.Split("This is a sentence");
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.
Based on existing responses on this post, this simplify the implementation :)
namespace System
{
public static class BaseTypesExtensions
{
/// <summary>
/// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
/// </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
}
}
string s = "This is a sentence.";
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None);
for(int i=0; i<res.length; i++)
Console.Write(res[i]);
EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you only want the word "is" removed from the sentence and the word "this" to remain intact.
...In short:
string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);
Or use this code; ( same : new String[] )
.Split(new[] { "Test Test" }, StringSplitOptions.None)
You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.
Here is an extension function to do the split with a string separator:
public static string[] Split(this string value, string seperator)
{
return value.Split(new string[] { seperator }, StringSplitOptions.None);
}
Example of usage:
string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="to=xxx#gmail.com=yyy#yahoo.co.in";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1]=xxx#gmail.com=yyy#yahoo.co.in
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

Categories