This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 5 years ago.
Here is some basic simple code, where I want to process a string. Due to my requirements I have to replace a . with a , so that the further string to double parsing will work. For some reason the .s don't get replaced.
Sample code:
string[] pointArray = "3066.4735709236,4659.65039509825".Trim().Split(',');
foreach (var point in pointArray)
{
point.Replace('.',',');
}
//just checking for `.` in those strings
//a MessageBox pops up, because there are still `.` in the strings
Array.ForEach(pointArray, foo => { foo.Contains('.'); MessageBox.Show("has been not replaced"); });
What do I overlook?
string[] pointArray = "3066.4735709236,4659.65039509825".Trim().Split(',');
for (int i = 0; i < pointArray.Length; i++)
{
pointArray[i] = pointArray[i].Replace('.',',');
}
String are immutable, you have to set the value.
(Just a note, you have to use a for loop, because foreach doesn't allow item ti be modified.)
You can convert your source string to doubles array with linq:
var srcString = "3066.4735709236,4659.65039509825";
var doubles = srcString
.Trim()
.Split(',')
.SelectMany(s => s.Split('.').Select(double.Parse))
.ToArray();
This code will split your string by , then by . and convert each substring to double
Related
This question already has answers here:
Put result of String.Split() into ArrayList or Stack
(5 answers)
Closed 2 years ago.
I was wondering if there is a way to convert example:
'Hello.World' into '["Hello"]["World"]' or 'This.is.a.string' into ["This"]["is"]["a"]["string"]
I'm kinda new to C# and I was wondering if that's even possible using string formatting or something like that.
You can use the Split method like this string[] strings = String.Split("."); This will split your string per each period.
If you meant to include the single quotes (') as part of the string then:
String test = "'Hello.World'";
// Strip the first and last '
test = test.Substring(1, test.Length - 2);
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
// and add back in the single quotes
var result = $"'{String.Join("", split.Select(word => $"[\"{word}\"]"))}'";
Prints:
'["Hello"]["World"]'
If they just meant to surround your input then just:
String test = "Hello.World";
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
var result = $"{String.Join("", split.Select(word => $"[\"{word}\"]"))}";
Prints: ["Hello"]["World"]
This question already has answers here:
Convert a list of strings to a single string
(6 answers)
Closed 6 years ago.
I'm new to C#, and apologies for the noob question - I'm trying to convert a list of strings to a single string so I can use it with WWWForm's POST function.
If I have a list of strings (e.g. kidIds = ["a#123", "b#123"]), how do I easily convert it to a single string ("a#123, b#123")? In Javascript, I would simply do kidIds.join(","), but I'm not sure how to do it in C#.
I tried doing kidIds.ToArray().ToString(), but it's not really giving me what I want. I could loop through the entire list using a for loop, but I was wondering if there's a simpler one liner I could use?
Since you are new to C# I would like to tell you that, you were trying to convert a list of strings to a single string. No it is not a list of string but it is a array of string. List of strings would be initalize like
List<string> SomeName = new List<string>();
Where as your one is declared as array. Now you can Join the Array of strings into one string as same as Javascript like
string SomeString = String.Join(",", kidIds);
The string.Join method combines many strings into one. It receives two arguments: an array (or IEnumerable) and a separator string.
You can also create one string out of the String array using + that would concatenate the strings like
string smstr = String.Empty;
for(int i=0; i<kidIds.Length; i++)
{
smstr = smstr + kidIds[i];
//or
smstr += kidIds[i]
}
You can also choose StringBuilder to create one string out of array of strings since StringBuilder.Append() method is much better than using the + operator like
StringBuilder sb = new StringBuilder();
for(int i=0;i<kidIds.Length;i++)
{
sb.Append(kidIds[i]);
}
But StringBuilder is good when the concatenations are less than 1000, String.Join() is even more efficient than StringBuilder.
There is basically the same thing as JavaScript's join()
String.Join Method
Use String.Join(',', kidIds);
https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx
Perhaps you can try the function concat, like
String str = "";
str = kidIds[0] + kidIds[1];
or
str = str.concat(kidIds[0], kidIds[0]);
or
for(int i=0;i<length;i++)
{
str += kidIds[i];
}
I think i would help.
You can do this using following code...
string[] kidIds = { "a#123", "b#123" };
String str = "";
foreach (var kidId in kidIds)
{
str += kidId + ",";
}
str = str.Remove(str.Length - 1,1); // this line use for remove last comma
thanks...
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]);
}
}
This question already has answers here:
Split String in C#
(9 answers)
Closed 7 years ago.
I've a string like this
cscript "E:\Data\System Test Performance\Some Tool\script.vbs" "AP_TEST" %%PARM1
I'm splitting above string like below
cmd.Split(' ')
Expected:
cscript
"E:\Data\System Test Performance\Some Tool\script.vbs"
"AP_TEST"
%%PARM1
But Actual results
There is a space in the string so your result is as expected. Try splitting on the quote instead:
var str = #"cscript ""E:\Data\System Test Performance\Some Tool\script.vbs"" ""AP_TEST"" %%PARM1";
str.Split('"').Select (s => s.Trim()).Where (s => !string.IsNullOrEmpty(s));
You need to write your own split function which supports text qualifiers
Check answer here Split String in C#
Or this article http://www.codeproject.com/Articles/15361/Split-Function-that-Supports-Text-Qualifiers
This might do the trick for you
string[] newinp = Regex.Split(inp, "(?=\")").Where(x => !string.IsNullOrEmpty(x)).ToArray();
There are so many spaces in your E:\Data\System Test Performance\Some Tool\script.vbs (file location) thats why you're getting the wrong array.
You may do two things
1) Make directory which doesn't contains spaces
2) Modify code
string[] final=new string[4];
final[0]=cmdLinesplit[0];
final[2]=cmdLinesplit[cmdLinesplit.Length-2];
final[3]=cmdLinesplit[cmdLinesplit.Length-1];
for(int i=1;i< cmdLinesplit.Length-2;i++)
{
final[1] +=cmdLinesplit[i]+" ";
}
final[1].Trim();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Split string, convert ToList<int>() in one line
Convert comma separated string of ints to int array
I have a string like:
string test = "1,2,3,4";
Is there any easier way (syntactically) to convert it to a List<int> equivalent to something like this:
string[] testsplit = test.Split(',');
List<int> intTest = new List<int>();
foreach(string s in testsplit)
intTest.Add(int.Parse(s));
You can throw LINQ at it:
List<int> intTest = test.Split(',').Select(int.Parse).ToList();
It first splits the string, then parses each part(returning an IEnumerable<int>) and finally constructs a list from the integer sequence.
var result = test.Split(',').Select(x => int.Parse(x));
Or, if you really want a List<int> (rather than just any IEnumerable<int>), append a .ToList().
test.Split(',').Select(x => int.Parse(x)).ToList()
Linq can make it a bit cleaner:
var intTest = test.Split(',').Select(s=>int.Parse(s)).ToList();