I am trying to split each column value from the string variable. The value is coming from an excel comma seperated file. how can I split each column from each string
string1= "\"1\",\"Truck\",\"FN60HZU\",\"'WC\",,\"26/03/2022\",\"H2\",\"NEARSIDE OUTER\",\"1\",\"31580225\",\"TRIANGLE\",\"TRS02\",\"14\",\"14\",\"14\",,\"17\",\"5TST001\",\"16:01:00\",\"16:07:16\",\"40:D3:AE:CB:16:EE\""
string2 = "\"1\",\"Truck\",\"FN60HZU\",\"'WC\",,\"26/03/2022\",\"H2\",\"OFFSIDE OUTER\",\"2\",\"29580225\",\"FROMWAY\",\"HD919\",\"15\",\"15\",\"15\",,\"17\",\"5TST001\",\"16:01:00\",\"16:07:16\",\"40:D3:AE:CB:16:EE\""
string3= "\"1\",\"Truck\",\"FN60HZU\",\"'WC\",,\"26/03/2022\",\"H2\",\"NEARSIDE INNER\",\"2\",\"29580225\",\"GOODYEAR\",\"KMAXD\",\"12\",\"12\",\"12\",,\"17\",\"5TST001\",\"16:01:00\",\"16:07:16\",\"40:D3:AE:CB:16:EE\""
I created function which I used Regex to split csv line accordingly.
public static string[] CSVReadlineToArray(this string fReadLine)
{
string[] _ReturnThis = null;
Regex rexCsvSplitter = new Regex(#",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");
_ReturnThis = rexCsvSplitter.Split(fReadLine);
return _ReturnThis;
}
//I know this is a dumb answer (?) lmao, but I've experienced like this before.
//Just simply replace the current delimiter into new delimiter then split with your new delimiter.
//This one works for me.
yourstring.Replace("\",\"", "|");
This program splits your string and writes each column in its own row:
using System;
class Program {
public static void Main(string[] args) {
var string1="\"1\",\"Truck\",\"FN60HZU\",\"'WC\",,\"26/03/2022\",\"H2\",\"NEARSIDE OUTER\",\"1\",\"31580225\",\"TRIANGLE\",\"TRS02\",\"14\",\"14\",\"14\",,\"17,18,19\",\"5TST001\",\"16:01:00\",\"16:07:16\",\"40:D3:AE:CB:16:EE\"";
var columns = string1.Replace("\",\"", "|").Replace(",,", "||").Replace("\"","").Split('|');
foreach(var col in columns)
{
Console.WriteLine(col);
}
}
}
Test it here: https://dotnetfiddle.net/0C8nLP
Output:
1
Truck
FN60HZU
'WC
26/03/2022
H2
NEARSIDE OUTER
1
31580225
TRIANGLE
TRS02
14
14
14
17,18,19
5TST001
16:01:00
16:07:16
40:D3:AE:CB:16:EE
Related
I was trying to create a list from a user input with something like this:
Create newlist: word1, word2, word3, etc...,
but how do I get those words one by one only by using commas as references going through them (in order) and placing them into an Array etc? Example:
string Input = Console.ReadLine();
if (Input.Contains("Create new list:"))
{
foreach (char character in Input)
{
if (character == ',')//when it reach a comma
{
//code goes here, where I got stuck...
}
}
}
Edit: I didn`t know the existence of "Split" my mistake... but at least it would great if you could explain me to to use it for the problem above?
You can use this:
String words = "word1, word2, word3";
List:
List<string> wordsList= words.Split(',').ToList<string>();
Array:
string[] namesArray = words.Split(',');
#patrick Artner beat me to it, but you can just split the input with the comma as the argument, or whatever you want the argument to be.
This is the example, and you will learn from the documentation.
using System;
public class Example {
public static void Main() {
String value = "This is a short string.";
Char delimiter = 's';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
}
}
The example displays the following output:
Thi
i
a
hort
tring.
I have the the following string [5111110233857£254736283045£1000£25£212541£20120605152412
£KEN£NAI],[5111110233858£254736283045£2500£25£257812£2012
0605152613£KEN£NAI]. The comma separated strings are derived from a web service and the number depends on the records returned.
Now, the fields are separated by pound sign (£). I want to extract each field and save to database.
I have tried string.split() but i don't know how to use it on unknown number of strings.
What you can do here is Split by the comma, remove the [ and ] in each record then Split by the pound sign, example:
string test = "[5111110233857£254736283045£1000£25£212541£20120605152412 £KEN£NAI],[5111110233858£254736283045£2500£25£257812£20120605152613£KEN£NAI]";
string[] commaSeperatedStrings = test.Split(',').Select(s => s.Substring(1, s.Length - 2)).ToArray();
foreach (string commaSeperatedString in commaSeperatedStrings)
{
string[] numbers = commaSeperatedString.Split('£');
foreach (string number in numbers)
{
// You can int.Parse each number and work with them now
}
}
A little program that will remove the brackets, split on comma, then split on pound sign, using foreach loops instead of using lambda statements (easier to understand for some).
class Program
{
static void Main(string[] args)
{
string s = "[5111110233857£254736283045£1000£25£212541£20120605152412 £KEN£NAI],[5111110233858£254736283045£2500£25£257812£2012 0605152613£KEN£NAI]";
s = s.Replace("[", "").Replace("]", "");
var split_s = s.Split(',');
List<string> ans = new List<string>();
foreach(var x in split_s)
{
var t = x.Split('£');
foreach(var y in t)
{
ans.Add(y);
}
}
foreach(var x in ans)
{
Console.WriteLine(x);
}
Console.WriteLine("Press any key");
Console.ReadKey();
}
}
Using a `List', this is a dynamic array which you can add elements as you go, regardless of the number of values in your original string.
So I am coding a converter program that convers a old version of code to the new version you just put the old text in a text box and it converts Txt to Xml and im trying to get each items beetween two characters and below is the string im trying to split. I have put just the name of the param in the " " to protect my users credentials. So i want to get every part of code beetween the ","
["Id","Username","Cash","Password"],["Id","Username","Cash","Password"]
And then add each string to a list so it would be like
Item 1
["Id","Username","Cash","Password"]
Item 2
["Id","Username","Cash","Password"]
I would split it using "," but then it would mess up because there is a "," beetween the params of the string so i tried using "],"
string input = textBox1.Text;
string[] parts1 = input.Split(new string[] { "]," }, StringSplitOptions.None);
foreach (string str in parts1)
{
//Params is a list...
Params.Add(str);
}
MessageBox.Show(string.Join("\n\n", Params));
But it sort of take the ] of the end of each one. And it messes up in other ways
This looks like a great opportunity for Regular Expressions.
My approach would be to get the row parts first, then get the column parts. I'm sure there are about 30 ways to do this, but this is my (simplistic) approach.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var rowPattern = new Regex(#"(?<row>\[[^]]+\])", RegexOptions.Multiline | RegexOptions.ExplicitCapture);
var columnPattern = new Regex(#"(?<column>\"".+?\"")", RegexOptions.Multiline | RegexOptions.ExplicitCapture);
var data = "[\"Id\",\"Username\",\"Cash\",\"Password\"],[\"Id\",\"Username\",\"Cash\",\"Password\"]";
var rows = rowPattern.Matches(data);
var rowCounter = 0;
foreach (var row in rows)
{
Console.WriteLine("Row #{0}", ++rowCounter);
var columns = columnPattern.Matches(row.ToString());
foreach (var column in columns)
Console.WriteLine("\t{0}", column);
}
Console.ReadLine();
}
}
}
Hope this helps!!
You can use Regex.Split() together with positive lookbehind and lookahead to do this:
var parts = Regex.Split(input, "(?<=]),(?=\\[)");
Basically this says “split on , with ] right before it and [ right after it”.
Assuming that the character '|' does not occur in your original data, you can try:
input.Replace("],[", "]|[").Split(new char[]{'|'});
If the pipe character does occur, use another (non-occurring) character.
I need to figure out how to remove the end of a string. The only trouble is, the string itself is not set. All I want to keep is the first 3-4 characters in the string.
string Location = "110 - Main Road";
string Location = "123 - Highway";
string Location = "234 - My House";
It could also be;
string Location = "1120 - Main Road";
I know if I can cut it down to the first 4 characters, I can just use .Trim() to remove the white spaces if it is only 3 characters, but I don't know how to cut it down to the first 4 characters?
You can use Split and get your number like this:
string Location = "1120 - Main Road";
int number = int.Parse(Location.Split()[0]);
This should work if there is no white-space before the number.If there is then use StringSplitOptions.RemoveEmptyEntries:
int number = int.Parse(Location.Split(new []{ ' ' },
StringSplitOptions.RemoveEmptyEntries)[0]);
split on spaces, then grab whatever is first, ignore the rest.
string GrabNumber(string input)
{
return input.Split(' ')[0];
}
assuming you want it as an integer you can take it a step further:
int GrabNumber(string input)
{
return int.Parse(input.Split(' ')[0]);
}
You can use String.Split() function to split your string based on delimeter - and then you can convert the first part of the string into integer if you want it in a Integer variable.
Solution 1: if you want to get first part of string as as string.
string Location = "11056 - Main Road";
Location = Location.Split('-')[0].Trim();
Solution 2: if you want to get the first part of the string as integer value.
string Location = "11056 - Main Road";
int num;
int.TryParse(Location.Split('-')[0],out num);
Just use a Substring call with a String.IndexOf, for example
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
List<string> strings = new List<string>();
strings.Add("110 - Main Road");
strings.Add("1104 - Main Road");
strings.Add("11088 - Main Road");
foreach(string s in strings){
Console.WriteLine(s.Substring(0,s.IndexOf("-",0)-1));
}
}
}
That way even if the street number is 4,5,6,7 characters long this will still work
If you just want the first 4 characters you would do this:
Location = Location.Substring(0, 4);
The first argument is the start position and the second argument is the length.
use the substring function of string(startIndex,numberOfCharToKeep) like this:
string Location = "110 - Main Road";
string NewLocation = Location.SubString(0,4);
this keeps your first 4 chars
Depends on how reliable your input is. If you will always have a space after the numbers you can find that location using IndexOf. However, whenever I work with strings I prefer regular expressions. Here is an example of both approaches:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string[] locations =
{
"110 - Main Road",
"123 - Highway",
"234 - My House",
"1120 - Main Road"
};
Regex r = new Regex(#"^\d+");
foreach (string location in locations)
{
Console.WriteLine(location.Substring(0, location.IndexOf(' ')));
Console.WriteLine(r.Match(location).Captures[0].Value);
}
}
}
I have a large string, where there can be specific words (text followed by a single colon, like "test:") occurring more than once. For example, like this:
word:
TEST:
word:
TEST:
TEST: // random text
"word" occurs twice and "TEST" occurs thrice, but the amount can be variable. Also, these words don't have to be in the same order and there can be more text in the same line as the word (as shown in the last example of "TEST"). What I need to do is append the occurrence number to each word, for example the output string needs to be this:
word_ONE:
TEST_ONE:
word_TWO:
TEST_TWO:
TEST_THREE: // random text
The RegEx for getting these words which I've written is ^\b[A-Za-z0-9_]{4,}\b:. However, I don't know how to accomplish the above in a fast way. Any ideas?
Regex is perfect for this job - using Replace with a match evaluator:
This example is not tested nor compiled:
public class Fix
{
public static String Execute(string largeText)
{
return Regex.Replace(largeText, "^(\w{4,}):", new Fix().Evaluator);
}
private Dictionary<String, int> counters = new Dictionary<String, int>();
private static String[] numbers = {"ONE", "TWO", "THREE",...};
public String Evaluator(Match m)
{
String word = m.Groups[1].Value;
int count;
if (!counters.TryGetValue(word, out count))
count = 0;
count++;
counters[word] = count;
return word + "_" + numbers[count-1] + ":";
}
}
This should return what you requested when calling:
result = Fix.Execute(largeText);
i think you can do this with Regax.Replace(string, string, MatchEvaluator) and a dictionary.
Dictionary<string, int> wordCount=new Dictionary<string,int>();
string AppendIndex(Match m)
{
string matchedString = m.ToString();
if(wordCount.Contains(matchedString))
wordCount[matchedString]=wordCount[matchedString]+1;
else
wordCount.Add(matchedString, 1);
return matchedString + "_"+ wordCount.ToString();// in the format: word_1, word_2
}
string inputText = "....";
string regexText = #"";
static void Main()
{
string text = "....";
string result = Regex.Replace(text, #"^\b[A-Za-z0-9_]{4,}\b:",
new MatchEvaluator(AppendIndex));
}
see this:
http://msdn.microsoft.com/en-US/library/cft8645c(v=VS.80).aspx
If I understand you correctly, regex is not necessary here.
You can split your large string by the ':' character. Maybe you also need to read line by line (split by '\n'). After that you just create a dictionary (IDictionary<string, int>), which counts the occurrences of certain words. Every time you find word x, you increase the counter in the dictionary.
EDIT
Read your file line by line OR split the string by '\n'
Check if your delimiter is present. Either by splitting by ':' OR using regex.
Get the first item from the split array OR the first match of your regex.
Use a dictionary to count your occurrences.
if (dictionary.Contains(key)) dictionary[key]++;
else dictionary.Add(key, 1);
If you need words instead of numbers, then create another dictionary for these. So that dictionary[key] equals one if key equals 1. Mabye there is another solution for that.
Look at this example (I know it's not perfect and not so nice)
lets leave the exact argument for the Split function, I think it can help
static void Main(string[] args)
{
string a = "word:word:test:-1+234=567:test:test:";
string[] tks = a.Split(':');
Regex re = new Regex(#"^\b[A-Za-z0-9_]{4,}\b");
var res = from x in tks
where re.Matches(x).Count > 0
select x + DecodeNO(tks.Count(y=>y.Equals(x)));
foreach (var item in res)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
private static string DecodeNO(int n)
{
switch (n)
{
case 1:
return "_one";
case 2:
return "_two";
case 3:
return "_three";
}
return "";
}