How to split a string by a specific character? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do i split a String into multiple values?
I have a string 0001-102525 . I want to split it into 0001 and 102525.How can i do it?
Regards,

var myString = "0001-102525";
var splitString = myString.Split("-");
Then access either like so:
splitString[0] and splitString[1]
Don't forget to check the count/length if you are splitting user inputted strings as they may not have entered the '-' which would cause an OutOfRangeException.

How about:
string[] bits = text.Split('-');
// TODO: Validate that there are exactly two parts
string first = bits[0];
string second = bits[1];

You can use C# split method - MSDN

string strData = "0001-102525";
//Using List
List<string> strList = strData.Split('-').ToList();
string first = strList.First();
string last = strList.Last();
//Using Array
string[] strArray = strData.Split('-');
string firstItem = strArray[0];
string lastItem = strArray[1];

string myString = "0001-102525";
//to split the string
string [] split = myString.Split("-");
//to display the new strings obtained to console
foreach(string s in split)
{
if(s.Trim() !="")
Console.WriteLine(s);
}

string strToSplit = "0001-102525"; //Can be of any length and with many '-'s
string[] arrStr = strToSplit.Split('-');
foreach (string s in arrStr) //strToSplit can be with many '-'s. This foreach loop to go thru entire arrStr string array
{
MessageBox.Show(s);
}

Related

Get a string inside a string

string a = "100-0-6-7-6-10-8-" //and so on
/////////////////////////////////////////////
//my solution
char[] delimiterChars = {'-'};
string solution = "100-0-6-7-6-10-8-";
string[] words = solution.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
//ok so i encounter some problems when trying to overwrite 0s, and 10s,100s etc
//so when writing data to the "solution" string it should be
//"-100--0--6--7--6--10--8-" instead of "100-0-6-7-6-10-8-"
basically, I want to separate each number and put it in a list or array
i think i got it
char[] delimiterChars = {'-'};
string text = "100-0-6-7-6-10-8-";
string[] words = text.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
This solution using Linq works as well.
var text="100-0-6-7-6-10-8-";
var words=text.Split("-").Where(x => !string.IsNullOrEmpty(x)).ToArray();

How can I remove empty string from an array of string in C#? [duplicate]

This question already has answers here:
c# split string and remove empty string
(6 answers)
Closed 3 years ago.
I have the following problem with this .NET C# application.
I have this string array:
string[] uorsList = uors.Split(';');
Sometimes this array contains an element corresponding to the empty string ("").
What is a smart way to remove all the element that are empty string from this uorsList array?
You can use LINQ to filter out the empty entires:
using System.Linq;
...
string[] uorsList = uors.Split(';');
var filtered = uorsList.Where(s=> !string.IsNullOrWhiteSpace(s)).ToArray();
EDIT:
As pointed out in comments, when using string.Split the following is a better option as the empty entries will never make it into the array:
string[] uorsList = uors.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
These are some ways to do it:
string uors = ";bla;bla;";
string[] uorsList = uors.Split(';').Where(x => string.IsNullOrEmpty(x) == false).ToArray();
string uors = ";bla;bla;";
string[] uorsList = uors.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
string uors = ";bla;bla;";
List<string> uorsList = uors.Split(';').ToList();
uorsList.RemoveAll(x => string.IsNullOrEmpty(x));
You can try the following :
string[] uorsList = uors.Split(';').Where(s => s != string.IsNullOrWhiteSpace).ToArray();

When i used String.Split the subsequent array only contains the first value? [duplicate]

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 6 years ago.
After reading a text file, I pass the information through a method that splits the string to get the required information for each field. I have gotten to the point where i split the string based on new lines, but it is beyond me why when I display the subsequent array (or list it's converted to), it only shows the first half of the first split string.
An example of how the input string looks:
ASSIGNMENT
In-Class Test 02/07/2014
In-Class Test 21/04/2013
Find my code below (the numLines variable was to simply see if it was being split into the correct number of lines as it should)
private void assignmentfinder(string brief, string id)
{
string searchcrit = "ASSIGNMENT";
string assignment = brief.Substring(brief.IndexOf(searchcrit) + searchcrit.Length);
string[] assignmentsplit;
assignmentsplit = assignment.Split('\t');
List<string> Assign = new List<string>(assignmentsplit);
listBox2.DataSource = Assign;
int numLines = assignment.Split('\n').Length;
richTextBox1.Lines=(assignmentsplit);
}
The output I get is:
In-Class Test
02/07/2014
Whereas it should show the second string split as well. Any ideas?
The problem is in the value of "brief" variable. Make sure the value you are putting in "brief" variable, actually conains "\n" and "\t".
You could use regex like this:
private void assignmentfinder(string brief, string id)
{
Regex rgxLines = new Regex(#"^(.*?)[ \t]+([0-9]{2}\/[0-9]{2}\/[0-9]{4})", RegexOptions.Multiline);
MatchCollection mLines = rgxLines.Matches(brief);
foreach (Match match in mLines)
{
richTextBox1.Text += String.Format("Test: {0}{1}Date: {2}{1}{1}",
match.Groups[1].Value,
Environment.NewLine,
match.Groups[2].Value);
}
}
Your mistake is that you split for each tab (\t). Split for the new line as you say:
private void assignmentfinder(string brief, string id)
{
string searchcrit = "ASSIGNMENT";
string assignment = brief.Substring(brief.IndexOf(searchcrit) + searchcrit.Length);
string[] assignmentSplit = assignment.Split('\n'); // splitting at new line
richTextBox1.Lines = assignmentSplit;
listBox2.DataSource = assignmentSplit.ToList();
}
I hope this helps.
EDIT: Just fixed a huge mistake
Question: Is it on purpose that the string id is never used?
You could use Linq to split on new line, then on tab, skipping the first line then aggregate into a list of string:
string brief = #"ASSIGNMENT
In-Class Test 02/07/2014
In-Class Test 21/04/2013";
List<string> theLines = new List<string>();
var lines = brief.Split('\n').Skip(1).Select (b => b.Split('\t'));
foreach (var line in lines)
{
for (int i = 0; i < line.Length; i++)
{
theLines.Add(line[i]);
}
}

Read specific values out of a text-file and put them in a list

I have a text-file with many lines, each line looks like this:
"string string double double" between each value is a space. I'd like to read out the first string and last double of every line and put these two values in a existing list. That is my code so far, but it doesnt really work.
private void bOpen_Click(object sender, RoutedEventArgs e)
{
bool exists = File.Exists(#"C:\Users\p2\Desktop\Liste.txt");
if (exists == true)
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\Liste.txt"))
{
Vgl comp = new Vgl();
comp.name = Abzahlungsdarlehenrechner.zgName;
comp.gErg = Abzahlungsdarlehenrechner.zgErg;
GlobaleDaten.VglDaten.Add(comp);
int i = 0;
string line = File.ReadLines(#"Liste.txt").Skip(0).Take(1).First();
while ((line = sr.ReadLine()) != null)
{
sb.Append((line));
listBox.Items.Add(line);
GlobaleDaten.VglDaten.Add(comp);
i++;
}
}
}
I have already read this, but it didnt help How do I read specific value[...]
You can try Linq:
var source = File
.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(line => line.Split(' '))
.Select(items => new Vgl() {
name = items[0],
gErg = double.Parse(items[3])
});
// If you want to add into existing list
GlobaleDaten.VglDaten.AddRange(source);
// If you want to create a new list
//List<Vgl> list = source.ToList();
how about
List<Vgl> Result = File.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(x => new Vgl()
{
name = x.Split(' ').First(),
gErg = decimal.Parse(x.Split(' ').Last(), NumberStyles.AllowCurrencySymbol)
})
.ToList();
I would avoid storing money within doulbe values because this could lead to rounding issues. Use decimal instead. Examples here: Is a double really unsuitable for money?
You can use:
string[] splitBySpace = line.Split(' ');
string first = splitBySpace.ElementAt(0);
decimal last = Convert.ToDecimal(splitBySpace.ElementAt(splitBySpace.Length - 1));
Edit : To Handle Currency symbol:
string[] splitBySpace = line.Split(' ');
string pattern = #"[^0-9\.\,]+";
string first = splitBySpace.ElementAt(0);
string last = (new Regex(pattern)).Split(splitBySpace.ElementAt(splitBySpace.Length - 1))
.FirstOrDefault();
decimal lastDecimal;
bool success = decimal.TryParse(last, out lastDecimal);
I agree with #Dmitry and fubo, if you are looking for alternatives, you could try this.
var source = File
.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(line =>
{
var splits = line.Split(' '));
return new Vgl()
{
name = splits[0],
gErg = double.Parse(splits[3])
};
}
use string.split using space as the delimiter on line to the string into an array with each value. Then just access the first and last array element. Of course, if you aren't absolutely certain that each line contains exactly 4 values, you may want to inspect the length of the array to ensure there are at least 4 values.
reference on using split:
https://msdn.microsoft.com/en-us/library/ms228388.aspx
Read the whole file as a string.
Split the string in a foreach loop using \r\n as a row separator. Add each row to a list of strings.
Iterate through that list and split again each record in another loop using space as field separator and put them into another list of strings.
Now you have all the four fields containig one row. Now just use First and Last methods to get the first word and the last number.

C# Best way to retrieve strings that's in quotation mark?

Suppose I am given a following text (in a string array)
engine.STEPCONTROL("00000000","02000001","02000043","02000002","02000007","02000003","02000008","02000004","02000009","02000005","02000010","02000006","02000011");
if("02000001" == 1){
dimlevel = 1;
}
if("02000001" == 2){
dimlevel = 3;
}
I'd like to extract the strings that's in between the quotation mark and put it in a separate string array. For instance, string[] extracted would contain 00000000, 02000001, 02000043....
What is the best approach for this? Should I use regular expression to somehow parse those lines and split it?
Personally I don't think a regular expression is necessary. If you can be sure that the input string is always as described and will not have any escape sequences in it or vary in any other way, you could use something like this:
public static string[] ExtractNumbers(string[] originalCodeLines)
{
List<string> extractedNumbers = new List<string>();
string[] codeLineElements = originalCodeLines[0].Split('"');
foreach (string element in codeLineElements)
{
int result = 0;
if (int.TryParse(element, out result))
{
extractedNumbers.Add(element);
}
}
return extractedNumbers.ToArray();
}
It's not necessarily the most efficient implementation but it's quite short and its easy to see what it does.
that could be
string data = "\"00000000\",\"02000001\",\"02000043\"".Replace("\"", string.Empty);
string[] myArray = data.Split(',');
or in 1 line
string[] data = "\"00000000\",\"02000001\",\"02000043\"".Replace("\"", string.Empty).Split(',');

Categories

Resources