C#_How to insert a string into each columns table SQL - c#

How to insert a string into each columns table SQL
Example, I have a string :
/Hanoi/a2.3b6.7c8.4/Tphcm/n7.2a5.2
I tried many ways, however I got this result:
I don't know anyway to insert it into a table, I want they look like:
Can you suggest any ideal for me, please?

This is my way how to do if i need to develop it.
class Program
{
static void Main(string[] args)
{
List<Location> locations = new List<Location>();
string foo = "/Hanoi/a2.3b6.7c8.4/Tphcm/n7.2a5.2";
var bo = foo.Remove(0, 1).Split('/'); // split data by '/'
// even bo elenment is address and odd element has specific data like number and letter
for (int i = 0; i < bo.Length; i = i + 2)
{
var str = bo[i]; // Address
var str1 = bo[i + 1]; // Letter and Number
var arrLetters = str1.Where(c => char.IsLetter(c)).ToArray(); // Get Letters
for (int j = 0; j < arrLetters.Length; j++)
{
string splittedLetter = string.Empty;
string number = string.Empty;
if (j+1 != arrLetters.Length)
{
splittedLetter = str1.Split(arrLetters[j + 1])[0];
number = Regex.Replace(splittedLetter, "[A-Za-z ]", "");
str1 = str1.Replace(splittedLetter, string.Empty);
}
else
{
number = Regex.Replace(str1, "[A-Za-z ]", "");
}
// add to list, db or where you want :)
locations.Add(new Location
{
Address = str,
Letter = arrLetters[j].ToString(),
Number = number
});
}
}
Console.ReadKey();
}
}
class Location
{
public string Address { get; set; }
public string Letter { get; set; }
public string Number { get; set; }
}
List members data like your db result.
I hope this solution help to you

Extract the required information from the input string mentioned /Hanoi/a2.3b6.7c8.4/Tphcm/n7.2a5.2 by the parameter "/"
a. split complete string in to an array
string str = "/Hanoi/a2.3b6.7c8.4/Tphcm/n7.2a5.2";
string[] words = str.Split('/');
b. Extract required data from the words array
Write a sql query/LINQ to insert each string/numbers in to the related columns
Let us know if you see any issues in implementing this.

Related

Is there a way to compare two strings in C# and get the differences only?

I am trying to compare two string in C# and get the differences between them i.e words which are not present in the other string ignoring cases and commas just focusing on the words. If one string contains two or multiple the and the second string has one the, it means this will be disregarded as it exists in both. Example I have two strings like below;
Cat meet's a dog
Cat meet's a dog and a bird
The difference between those two strings is and bird because it does not exist in the first one or vise versa and I want to get those two words and bird either in a List or a new string with spaces between them and in other words I want the words which are not present in the other string. Is there a way this can be done in C#?
Here's a way using LINQ. You don't need the "ToList()" part, but you mentioned that as one form of output you'd want:
string str1 = "Cat meet's a dog";
string str2 = "Cat meet's a dog and a bird";
string[] str1Words = str1.ToLower().Split(' ');
string[] str2Words = str2.ToLower().Split(' ');
var uniqueWords = str2Words.Except(str1Words).Concat(str1Words.Except(str2Words)).ToList();
// Do whatever you want with uniqueWords instead
Console.WriteLine($"output: {String.Join(" ", uniqueWords)}");
#ngdeveloper. This is my variant of your solution (had to post it in a separate answer because of the length):
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int shortestLenght;
int longestLenght;
bool firstIsLongest;
if (_firstStringArray.Length > _secondStringArray.Length)
{
firstIsLongest = true;
shortestLenght = _secondStringArray.Length;
longestLenght = _firstStringArray.Length;
}
else
{
firstIsLongest = false;
shortestLenght = _firstStringArray.Length;
longestLenght = _secondStringArray.Length;
}
for (int i = 0; i < shortestLenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = shortestLenght; i < longestLenght; i++)
{
if (firstIsLongest)
_stringsDiff._diffList1.Add(_firstStringArray[i]);
else
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
return _stringsDiff;
}
I wrote you a simple solution, hope it will help -
The main method is called 'Difference' it receive 2 strings to compare and return an object called StringDiff.
It runs 2 loops, first comparing between the two strings char by char and then adding the rest of the longer string.
The 'StringDiff' object is a class with 2 char lists that represnt the differences of each string.
In the main method i use String.join to convert the char lists to a string and print it.
internal class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("enter first string");
string firstString = Console.ReadLine();
Console.WriteLine("enter second string");
string secondString = Console.ReadLine();
StringsDiff _stringsDiff = Difference(firstString, secondString);
Console.WriteLine(
$"fist string difference: {string.Join("", _stringsDiff._diffList1)} / second string difference: {string.Join("", _stringsDiff._diffList2)}");
Console.WriteLine("/////////////////////////////////////");
}
}
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int lenght;
if (_firstStringArray.Length > _secondStringArray.Length)
{
lenght = _secondStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _secondStringArray.Length; i < _firstStringArray.Length; i++)
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
}
}
else
{
lenght = _firstStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _firstStringArray.Length; i < _secondStringArray.Length; i++)
{
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
return _stringsDiff;
}
class StringsDiff
{
public List<char> _diffList1 = new List<char>();
public List<char> _diffList2 = new List<char>();
}
}
Remember to use "string.join" to connect the lists objects if you need a string.

How to change an unknown number in a text file for C#?

I'm trying to create a "warning system" for my Discord Server's bot where when using the command, it'll pull information from a text file and then update it. I can somewhat envision what I want to happen step by step, but I'm confused at how to pull what would be reading from a file as an example:
bob#5368 3
mark#8459 6
cindy#1254 2
I only want to change the number behind the name, which I'm not quite sure how to basically find the user I'm looking for, and then pull the number and set that to 'totalWarn', add it up (totalWarn =+ warnNum), and then update that user with the new number.
Note: 'warningFile' is the file path that's already defined outside of this block of code.
public async Task warn(IGuildUser user, int warnNum, [Remainder] string reason)
{
int totalWarn = 0;
if (user == null)
await ReplyAsync("Please include a name");
if (warnNum <= 0)
await ReplyAsync("The warning level must increase by 1 or more.");
if (reason == null)
await ReplyAsync("Please include a reason.");
string nickName = user.Username;
//Check for whether text file exists or not.
if (!File.Exists(warningFile))
{
//Create the File
FileStream fs = File.Create(warningFile);
}
//Reads all the text in the file and puts it into an array.
string[] arr = File.ReadAllLines(warningFile);
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
}
totalWarn = +warnNum;
await Context.Channel.SendMessageAsync($"{user.Username}'s warning level has increased by {warnNum} for {reason}.\n"
+ $"Your warning level is now {totalWarn}. Please take this time to review the server rules.");
}
I'm not looking for somebody to complete it for me, just some help to push myself in the right direction as I'm completely lost, and the information regarding changing text isn't quite helpful.
Here is how to parse a line from the file using regex:
void Main()
{
string line = "bob#5368 3";
GuildUser user = new GuildUser( line );
user.Warnings++;
user.ToString().Dump();
}
public class GuildUser
{
public string Name { get; set;}
public int Id { get; set;}
public int Warnings { get; set;}
public GuildUser( string line )
{
Match match = Regex.Match( line, #"(.+)?#(\d+) (\d+)" );
if ( !match.Success ) throw new Exception( "Couldn't parse line: " + line );
Name = match.Groups[1].Value;
Id = int.Parse( match.Groups[2].Value );
Warnings = int.Parse( match.Groups[3].Value );
}
public override string ToString()
{
return $"{Name}#{Id} {Warnings}";
}
}
You could use File.ReadAllLines, File.WriteAllLines.
I'd probably use some linq as well.
I updated to add a "ToString" method to rewrite the line.
Then you can just add to the warnings and get the new string calling ToString().
Another way:
public static void stuff()
{
string name = "bob";
string firstNumber = "";
string secondNumber = "";
int lineIndex = 0;
List<string> lines = new List<string>(File.ReadAllLines(#"C:\Text.txt"));
foreach(string line in lines)
{
if(line.Contains(name))
{
lineIndex = lines.IndexOf(line);
string[] parts = line.Split('#');
name = parts[0];
firstNumber = parts[1].Split(' ')[0];
secondNumber = parts[1].Split(' ')[1];
firstNumber = (Convert.ToInt32(firstNumber) + 1).ToString();
/*
* instert code here for changing the number you want to change
*/
lines[lineIndex] = name + "#" + firstNumber + " " + secondNumber;
File.WriteAllLines(#"C:\Text.txt",lines.ToArray());
break;
}
}
}

c# regular expression getting specific string from string[CLOSE]

help i want to get the specific string from my string x="Glass 1 1000"; i want to get the string "Glass" only and save it to my string type.
int[] quanvalue = new int[2];
int x1 = 0;
string type = "";
string x="Glass 1 1000";
string[] numbers = Regex.Split(x, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int ib = int.Parse(value);
quanvalue[x1] = ib;
MessageBox.Show(quanvalue[0].ToString() + " " + quanvalue[1].ToString());
x1++;
}
else
{
// i want to get string from here
}
string sub = x.Substring(0, 5);
You can use a substring function to fetch the first 5 characters from x.
And save it in x itself

Finding formatted parts of result of .NET's string.Format

I'm using string.Format in a data-driven fashion - I know how many objects to format there are, but nothing else - and I'd like to find out which parts of the result are formatted objects and which parts come verbatim from the format string. (I intend to display the formatted result in the UI with the formatted parts "hot", so that they can be hovered over and clicked on to activate some UI related to the object that produced them.)
For example, suppose I call this hypothetical formatting function, passing in a particular format string, and (string)"fred" as object 0, and (int)50 as object 1. And suppose the result is (fred). I'd like to be able to determine that the 4 chars starting at index 1 are the result of formatting object 0, and that object 1 wasn't formatted. (Clearly the format string in this case was something like "{0}".)
Is there some built-in way of doing this?
(This feels like a generic .NET/CLR question - but in case it's relevant, I'm using C#.)
If you know just the format string and the resulting string, but not the parameters which were formatted, it is not possible to find them in the resulting string.
For instance, the following lines produce the same result:
string.Format("{0}{1}", "a", "bc")
string.Format("{0}{1}", "ab", "c")
You could also work with regular expressions, more specifically using a MatchEvaluator, so you could keep track of those indexes. I made an example, which you can customize for your application:
static void Main(string[] args)
{
var arg0 = (string)"fred";
var arg1 = (int)50;
var format = "{0}";
var result = Format(format, arg0, arg1);
for(int index = 0; index < result.Arguments.Length; index++)
{
if(String.IsNullOrEmpty(result.Arguments[index].Capture))
{
Console.WriteLine(
"Argument {0} with value {1} was unused",
index, result.Arguments[index].Value);
}
else
{
Console.WriteLine(
"Argument {0} with value {1} was used, starting at index {2}",
index, result.Arguments[index].Value,
result.Arguments[index].Index);
}
}
}
static Transformation Format(string format, params object[] args)
{
var value = new Transformation
{
Format = format,
Arguments = (args ?? new object[]{})
.Select (o => new Argument{ Value = o })
.ToArray()
};
value.Result = Regex.Replace(format, #"{(\d+)}", (match) =>
{
int index = Convert.ToInt32(match.Groups[1].Value);
if (index > args.Length) return "";
var #this = args[index];
var result = #this == null ? "" : #this.ToString();
value.Arguments[index].Index = match.Index;
value.Arguments[index].Capture = match.Value;
value.Arguments[index].Length = result.Length;
return result;
});
return value;
}
class Transformation
{
public string Format { get; set; }
public string Result { get; set; }
public Argument[] Arguments { get; set; }
}
class Argument
{
public object Value { get; set; }
public int Index { get; set; }
public int Length { get; set; }
public string Capture { get; set; }
}
In the end I wrote my own thing, as it sounded like there wasn't any built-in way of getting what I wanted, whether from an existing function or by hooking into something somewhere.
Firstly, an object to store the location in the result where each object's string was inserted:
public class FormattedStringPart
{
public int ObjectIndex { get; private set; }
public int StartIndex { get; private set; }
public int Length { get; private set; }
public FormattedStringPart(int objectIndex, int startIndex, int length)
{
ObjectIndex = objectIndex;
StartIndex = startIndex;
Length = length;
}
}
Then the function itself works through the format string, building up a StringBuilder is it goes. Either it adds chars verbatim, or it finds a format part, which it formats with string.Format keeping track of the indexes so it can make a new FormattedStringPart for the insertion. (The key thing that makes this quite easy is that you can just hand off the format part and the entire array of object to string.Format - so there's no need to look carefully at the format part to check for validity. Just pass it to string.Format and see what happens.)
public static string FormatString(string format,
object[] args,
out FormattedStringPart[] formattedParts)
{
var parts = new List<FormattedStringPart>();
var result = new StringBuilder();
int i = 0;
while (i < format.Length)
{
char c = format[i];
if (c == '{')
{
int j = format.IndexOf('}', i);
if (j < 0)
throw new FormatException("Missing '}'");
int startIndex = result.Length;
result.AppendFormat(format.Substring(i, (j - i) + 1), args);
++i;
// the AppendFormat call should have ensured there's a
// valid number following...
int objectIndex = 0;
while (format[i] >= '0' && format[i] <= '9')
{
objectIndex *= 10;
objectIndex += (int)(format[i] - '0');
++i;
}
parts.Add(new FormattedStringPart(objectIndex,
startIndex,
result.Length - startIndex));
i = j + 1;
}
else
{
result.Append(c);
++i;
}
}
if (parts.Count == 0)
formattedParts = null;
else
formattedParts = parts.ToArray();
return result.ToString();
}
Eagle-eyed string.Format fans will note that this isn't quite exactly like string.Format - this is not (yet?) important in my situation.

How can I read a text file and loop though repeating sections?

I have an ANSI 835 (text) file. For simplicity's sake it looks like this:
ISA*00
GS*Foo*12345
ST*835*000001
LX*1
CLP*123456
NM1*Lastname
REF*010101
DTM*20120512
SVC*393939
LQ*19
LX*2
CLP*23456
NM1*Smith
REF*58774
DTM*20120601
SVC*985146
LX*3
CLP*34567
NM1*Doe
REF*985432
DTM*20121102
SVC*864253
LQ*19
LQ*84
The records are broken up into LX segments. Everything after LX*1 is one record, everything after LX*2 is another record, and so on. I need to get certain items from each line, assign them to variables, and eventually add them as a row to a datagridview. Again for simplicity's sake, I have the following variables and here's what should go in each:
string ItemNumber should be the group of characters after the * in the CLP line
string LastName should be the group of characters after the * in the NM1 line
string Date should be the group of characters after the * in the REF line
string Error should be the group of characters after the * in the LQ line
The biggest problem I'm facing is that there may be more than one LQ line in each LX segment. In that case, the 2nd error can just be added to the end of the first error, separated by a comma.
I tried loading the file into a string array and going line by line, but I'm not sure how say "start at LX*1 and do stuff until you hit LX*2".
string[] lines = File.ReadAllLines(MyFile);
foreach (string line in lines)
{
string[] splitline = line.Split('*');
if (splitline[0] = "LX")
{
//this is where i need to loop through the next lines
//until i hit the next line starting with LX.
}
}
Any ideas? As always, thank you for your time!
Start with a simple data model:
public class LXRecord
{
public string ItemNumber { get; set; }
public string LastName { get; set; }
public string Date { get; set; }
public List<string> Errors { get; set; }
public LXRecord()
{
Errors = new List<String>();
}
}
Define your significant tokens:
public static class Tokens
{
public const string TOKEN_SPLITTER = "*";
public const string NEW_RECORD = "LX";
public const string ITEM_NUMBER = "CLP";
public const string LAST_NAME = "NM1";
public const string DATE = "REF";
public const string ERROR = "LQ";
}
Loop through the lines, do a switch/case on the tokens, and just start a new LXRecord when you see the "LX" flag:
List<LXRecord> records = new List<LXRecord>();
LXRecord currentRecord = null;
foreach(string line in lines)
{
int tokenIndex = line.IndexOf(Tokens.TOKEN_SPLITTER);
if (tokenIndex < 1 || tokenIndex == line.Length - 1) //no token or no value?
continue;
string token = line.Substring(0, tokenIndex);
string value = line.Substring(tokenIndex + 1);
switch(token)
{
case(Tokens.NEW_RECORD) :
currentRecord = new LXRecord();
records.Add(currentRecord);
break;
case(Tokens.ITEM_NUMBER) :
currentRecord.ItemNumber = value;
break;
case(Tokens.LAST_NAME) :
currentRecord.LastName = value;
break;
case(Tokens.DATE) :
currentRecord.Date = value;
break;
case(Tokens.ERROR) :
currentRecord.Errors.Add(value);
break;
}
}
Notice this way you can relatively easily ignore non-supported flags, add new flags, or add parsing (for example, ItemNumber could use Int32.Parse and store it as an integer, or "Date" could store a DateTime) In this case, I chose to store the errors as a List<String>, but you could comma delimit it instead if you wish. I also avoided splitting on the * character in case the content contained a second asterisk as well.
EDIT: From your comment, you can have some more complicated/specialized parsing in the case or moved into another method. Instead of the case I have above for "LAST_NAME", you could have:
case(Tokens.LAST_NAME) :
ParseName(currentRecord, value);
break;
Where ParseName is:
public static void ParseName(LXRecord record, string value)
{
int tokenIndex = value.IndexOf(Tokens.TOKEN_SPLITTER);
if (tokenIndex < 1 || tokenIndex == value.Length - 1) //no last name and first name?
{
record.LastName = value;
}
else
{
record.LastName = value.Substring(0, tokenIndex);
record.FirstName = value.Substring(tokenIndex + 1);
}
}
The token check might be tweaked there, but it should give you a good idea.

Categories

Resources