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();
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:
How can I fix this regex expression?
(3 answers)
Closed 3 years ago.
How can I use C# to parse a csv file like this?
"TeamName","PlayerName","Position" "Chargers","Philip Rivers","QB" "Colts","Peyton Manning","QB" "Patriots","Tom Brady","QB"
Notice that there are zero natural line breaks. Double-spaces that reside outside of the values are what differentiate one row from another.
Relevant:
line breaks lost in sql server
How do you view ALL text from an ntext or nvarchar(max) in SSMS?
Using #toto's ideas (and mine) in the comments, how about something like this.
Use a regex to parse each line, and then take the contents of each line and make it into a line by added a "\r\n" at the end of each line.
const string input =
"\"TeamName\",\"PlayerName\",\"Position\" \"Chargers\",\"Philip Rivers\",\"QB\" \"Colts\",\"Peyton Manning\",\"QB\" \"Patriots\",\"Tom Brady\",\"QB\"";
const string linePattern = "(?<Line>(\"[^\"]+\",?)+) ";
var lineRegex = new Regex(linePattern);
var linesText = lineRegex.Replace(input, "${Line}\r\n");
At the end of this, linesText looks like a regular quote delimited CSV file and you can parse it using regular tools. If I run this code, this is what linesText looks like:
"TeamName","PlayerName","Position"
"Chargers","Philip Rivers","QB"
"Colts","Peyton Manning","QB"
"Patriots","Tom Brady","QB"
You can try the following.
var content = File.ReadAllText(#"path/to/csv").Replace(" ", ";");
var result = content.Split(';');
foreach (var str in result)
{
Console.WriteLine(str);
}
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
This question already has answers here:
Make first letter of a string upper case (with maximum performance)
(42 answers)
Closed 7 years ago.
I have already taken a look at such posts like:
Format to first letter uppercase
How to capitalise the first letter of every word in a string
But none of these seem to actually work. I would have thought to start with that there would just be a:
.Capitalize();
Like there is:
.Lower(); & .Upper();
Are there any documentation or references regarding converting to a string like the following?
string before = "INVOICE";
To then becoming:
string after = "Invoice";
I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.
What about using ToUpper on the first char and ToLower on the remaining string?
string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
You can create a method that does something like this:
string UppercaseFirst(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
And use it like this:
string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);
to get this:
Thisstringlookshorrible
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# how to convert File.ReadLines into string array?
I have a text file that I want to make a String array from. The file is newline delimited. For example,
entry1
entry2
entry3
will make an array of {"entry1", "entry2", "entry3"}
EDIT: I am wanting to do this using DownloadString in WebClient
So you're just trying to split a string into an array that is delimited with a new line?
If so, this should work:
string temp = webClient.DownloadString(someurl);
string[] lines = temp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Good luck.