Splitting a String into only 2 parts - c#

I want to take a string from a textbox (txtFrom) and save the first word and save whatever is left in another part. (the whatever is left is everything past the first space)
Example string = "Bob jones went to the store"
array[0] would give "Bob"
array[1] would give "jones went to the store"
I know there is string[] array = txtFrom.Split(' '); , but that gives me an array of 6 with individual words.

Use String.Split(Char[], Int32) overload like this:
string[] array = txtFrom.Text.Split(new char[]{' '},2);
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

You simply combine a split with a join to get the first element:
string[] items = source.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string firstItem = items[0];
string remainingItems = string.Join(" ", items.Skip(1).ToList());
You simply take the first item and then reform the remainder back into a string.

char[] delimiterChars = { ' ', ',' };
string text = txtString.Text;
string[] words = text.Split(delimiterChars, 2);
txtString1.Text = words[0].ToString();
txtString2.Text = words[1].ToString();

There is an overload of the String.Split() method which takes an integer representing the number of substrings to return.
So your method call would become: string[] array = txtFrom.Text.Split(' ', 2);

You can also try RegularExpressions
Match M = System.Text.RegularExpressions.Regex.Match(source,"(.*?)\s(.*)");
M.Groups[1] //Bob
M.Groups[2] // jones went to the store
The regular expression matches everything up to the first space and stores it in the first group the ? mark tells it to make the smallest match possible. The second clause grabs everything after the space and stores it in the second group

Related

How do I write code in C# to print the given string in the descending order of size of the word

The given string is first last middle begin end ; I should get the output like middle begin first last end?
This will do your job. Split and then sort by length.
string s = "first last middle begin end";
string[] words = s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).OrderByDescending(x=>x.Length).ToArray();
What you have here is a sorting problem. Figure out how to split the string into individual words, then sort by length, and then recombine them into one string.
Just separate the original String by Char ' ' (empty Space).
Then save these separations in String Array, or I prefer a List.
e.g.
string[] words = s.Split(' ');
Then you can loop through Array/List by Item-Length, display the words, delete the entry, loop again, ...
The result in your example also seems to be sorting alphabetically after sorting the words by length in descending order. Here is some code that uses Linq to perform both levels of the sort:
string s = "first last middle begin end";
s = string.Join(" ", s.Split(' ').OrderByDescending(item => item.Length).ThenBy(item => item).ToArray());
Console.WriteLine(s);

Split string into array that is enclosed in capturing parentheses

I have the following string in my project:
((1,01/31/2015)(1,Filepath)(1,name)(1,code)(1,String)(1, ))
I want to split this string into parts where i get the information within the capturing parentheses (for example 1,Filepath or (1,Filepath), but the whole string is in capturing parentheses too as you can see. The result i then try to put into array with string[] array = Regex.Split(originalString,SomeRegexHere)
Now i am wondering what would be the best approach be, just remove the first and last character of the string so i don't have the capturing parentheses enclosing the whole string, or is there some way to use Regular expressions on this to get the result i want to ?
string s = "((1,01/31/2015)(1,Filepath)(1,name)(1,code)(1,String)(1, ))";
var data = s.Split(new string[]{"(", ")"}, StringSplitOptions.RemoveEmptyEntries)
your Data would be then
["1,01/31/2015",
"1,Filepath",
"1,name",
"1,code",
"1,String",
"1,"]
You can create a substring without the first 2 and last 2 brackets and then split this on the enclosing brackets
var s = "((1,01/31/2015)(1,Filepath)(1,name)(1,code)(1,String)(1, ))";
var result = s.Substring(2, s.Length - 4)
.Split(new string[]{")("}, StringSplitOptions.RemoveEmptyEntries);
foreach(var r in result)
Console.WriteLine(r);
Output
1,01/31/2015
1,Filepath
1,name
1,code
1,String
1,
Example
(?<=\()[^()]*(?=\))
Just do a match and get your contents instead of splitting.See demo.
https://regex101.com/r/eS7gD7/15

How to remove Whitespce from stringArray formed based on whitespace

I have a string which contains value like.
90 524 000 1234567890 2207 1926 00:34 02:40 S
Now i have broken this string into string Array based on white-space.Now i want to create one more string array into such a way so that all the white-space gets removed and it contains only real value.
Also i want to get the position of the string array element from the original string array based on the selection from the new string array formed by removing white space.
Please help me.
You can use StringSplitOptions.RemoveEmptyEntries via String.Split.
var values = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries: The return value does not include array elements that contain an empty string
When the Split method encounters two consecutive white-space it will return an empty string.Using StringSplitOptions.RemoveEmptyEntries will remove the empty strings and give you only the values you want.
You can also achieve this using LINQ
var values = input.Split().Where(x => x != string.Empty).ToArray();
Edit: If I understand you correctly you want the positions of the values in your old array. If so you can do this by creating a dictionary where the keys are the actual values and the values are indexes:
var oldValues = input.Split(' ');
var values = input.Split().Where(x => x != string.Empty).ToArray();
var indexes = values.ToDictionary(x => x, x => Array.IndexOf(oldValues, x));
Then indexes["1234567890"] will give you the position of 1234567890 in the first array.
You can use StringSplitOptions.RemoveEmptyEntries:
string[] arr = str.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
Note that i've also added tab character as delimiter. There are other white-space characters like the line separator character, add as desired. Full list here.
string s = "90 524 000 1234567890 2207 1926 00:34 02:40 S ";
s.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x))

How to split string between different chars

I am having trouble splitting a string. I want to split only the words between 2 different chars:
string text = "the dog :is very# cute";
How can I grab only the words, is very, between the : and # chars?
You can use String.Split() method with params char[];
Returns a string array that contains the substrings in this instance
that are delimited by elements of a specified Unicode character array.
string text = "the dog :is very# cute";
string str = text.Split(':', '#')[1]; // [1] means it selects second part of your what you split parts of your string. (Zero based)
Console.WriteLine(str);
Here is a DEMO.
You can use it any number of you want.
That's not really a split at all, so using Split would create a bunch of strings that you don't want to use. Simply get the index of the characters, and use SubString:
int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
use this code
var varable = text.Split(':', '#')[1];
Regex regex = new Regex(":(.+?)#");
Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value);
One of the overloads of string.Split takes a params char[] - you can use any number of characters to split on:
string isVery = text.Split(':', '#')[1];
Note that I am using that overload and am taking the second item from the returned array.
However, as #Guffa noted in his answer, what you are doing is not really a split, but extracting a specific sub string, so using his approach may be better.
Does this help:
[Test]
public void split()
{
string text = "the dog :is very# cute" ;
// how can i grab only the words:"is very" using the (: #) chars.
var actual = text.Split(new [] {':', '#'});
Assert.AreEqual("is very", actual[1]);
}
Use String.IndexOf and String.Substring
string text = "the dog :is very# cute" ;
int colon = text.IndexOf(':') + 1;
int hash = text.IndexOf('#', colon);
string result = text.Substring(colon , hash - colon);
I would just use string.Split twice. Get the string to the right of the first separator. Then, using the result, get the string to the left of second separator.
string text = "the dog :is very# cute";
string result = text.Split(":")[1] // is very# cute";
.Split("#")[0]; // is very
It avoids playing around with indexes and regex which makes it more readable IMO.

Get a file/directory path from a string that contains other data

How would I get the directory and filename from the following string using C#:
string test = "test#test.com, snap555.jpg, c:\users\test\desktop\snap555.jpg";
I only want to be able to get the "c:\users\test\desktop\snap555.jpg" from the string and turn it into another string.
The characters before the "," will always be different and different lengths such as: "bob#bob.com, x.txt, c:\users\test\desktop\x.txt"
What is the easiest way to do this in c#?
Thanks.
t
If the comma delimiter does not appear in the first part, you can use:
string pathName = test.Split(',')[2];
If that space after the comma is a problem and assuming that the first part never has spaces, you can use:
char[] delims = new char[] { ',', ' '};
string pathName = test.Split(delims, StringSplitOptions.RemoveEmptyEntries)[2];
This example assumes you always want the third item, as mentioned in your question. Otherwise, change the 2 in the examples above to the correct index of the item you want. For example, if it should always be the last item, you can do:
char[] delims = new char[] { ',', ' '};
string[] items = test.Split(delims, StringSplitOptions.RemoveEmptyEntries);
string pathName = items[items.Length-1];
If there's always going to be a comma there you can use
string test = "snap555.jpg, c:\users\test\desktop\snap555.jpg";
string[] parts = test.Split(',');
Then get whatever you need from the parts array.

Categories