I have this class:
public class Student
{
private int[] note;//vector de note
private DateTime dataInrolarii;
private int nrRestante;
private readonly int nrMatricol;
private const string sex = "feminin"
public static int anStudiu = 3;
public Student(string cnp, string nume, int nrMatricol, DateTime dataInrolarii, int nrRestante, int[] note) : base(cnp, nume)
{
this.nrMatricol = nrMatricol;
this.dataInrolarii = Convert.ToDateTime(dataInrolarii);
this.nrRestante = nrRestante;
this.note = new int[note.Length];
for (int i = 0; i < note.Length; i++)
this.note[i] = note[i];
}
}
Of course, i have getters, setters, toString() overloaded and more.
I have a text file with this object :
2920118080023, George, 2, 12/09/2016, 4, 10 3 4
and I want to read from file and displat in a textBox the Students from file. but i don't really know how to do this with the vector note.
Here is that i wrote:
private void button_CitireTXT_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("citiretxt.txt");
string linie = null;
while ((linie = sr.ReadLine()) != null)
{
try
{//oricare ar fi tipul unui atribut citit din fisier, ele sunt STRING acolo
string cnp = linie.Trim().Split(',')[0];
string nume = linie.Trim().Split(',')[1];
int nrmat = Convert.ToInt32(linie.Trim().Split(',')[2]);
string datainrolString = linie.Trim().Split(',')[3];
DateTime datainrol = DateTime.Parse(datainrolString);
int nrRest = Convert.ToInt32(linie.Trim().Split(',')[4]);
string noteString = linie.Split(' ')[5];
for(int i=0;i< noteString.Length;i++)
{
noteString[i] = Convert.ToInt32(noteString[i]);
string[] notesString
}
Student s = new Student(cnp, nume, nrmat, datainrol, nrRest, note);
tb_CitireDinTxt.Text += s.ToString() + Environment.NewLine;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
How to read the vector NOTE from file? Thank you
UPDATE:
private void button_CitireTXT_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("citiretxt.txt");
string linie = null;
while ((linie = sr.ReadLine()) != null)
{
try
{
string cnp = linie.Trim().Split(',')[0];
string nume = linie.Trim().Split(',')[1];
int nrmat = Int32.Parse(linie.Trim().Split(',')[2]);
string datainrolString = linie.Trim().Split(',')[3];
DateTime datainrol = DateTime.Parse(datainrolString);
int nrRest = Int32.Parse(linie.Trim().Split(',')[4]);
int[] notes = Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse);
Student s1 = new Student(cnp, nume, nrmat, datainrol, nrRest, notes);
tb_CitireDinTxt.Text += s1.ToString() + Environment.NewLine;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Writing answer by considering, Vector(from C++) -> List(in C#).
If following is your file content,
2920118080023, George, 2, 12/09/2016, 4, 10 3 4
Split by ,. Then your string at 5th index will contain 10 3 4. Now to convert it into array of integer use Array.ConvertAll() or you can convert it to List as well
Try bellowed code
//Converting into int array
int[] notes = Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse)
//Converting into List<int>
List<int> notes= Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse).ToList()
Instead of
string noteString = linie.Split(' ')[5];
for(int i=0;i< noteString.Length;i++)
{
noteString[i] = Convert.ToInt32(noteString[i]);
string[] notesString
}
Related
I can't permanently replace the array members. When I change the value of String Clue, the string being displayed only displays the current value of clue. I think the problem us on the initialization of char[]. I tried to put them in other parts of the code but it produces error. Beginner here! Hope you can help me. Thanks! :)
private void clues(String clue)
{
int idx = numb[wordOn]+4;
char[] GuessHide = Words[idx].ToUpper().ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] != Convert.ToChar(clue.ToUpper()))
GuessHide[a] = '*';
else
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
Guess(string.Join("", GuessHide));
}
Edited - because you initalize GuessHide at each call of calls in your code and you do not store its current state you basically reset it each time. Still, you can make some small changes in your code like this:
private static void clues(string clue, char[] GuessHide, char[] GuessShow)
{
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] == Convert.ToChar(clue.ToUpper()))
{
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
}
Console.WriteLine(string.Join("", GuessHide));
}
Call it like this:
clues("p", GuessHide, GuessShow);
clues("a", GuessHide, GuessShow);
Initialise GuessShow and GuessHide in the outside code like this:
char[] GuessHide = new string('*', Words[idx].Length).ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
public class Program
{
static string[] Words;
static string[] HiddenWords;
public static void Main()
{
Words = new string[] { "Apple", "Banana" };
HiddenWords = new string[Words.Length];
for (int i = 0; i < Words.Length; i++)
{
HiddenWords[i] = new string('*', Words[i].Length);
}
Guess('P', 0);
Guess('a', 0);
Guess('A', 1);
Guess('N', 1);
Console.ReadLine();
}
private static void Guess(char clue, int idx)
{
string originalWord = Words[idx];
string upperedWord = Words[idx].ToUpper();
char[] foundSoFar = HiddenWords[idx].ToCharArray();
clue = char.ToUpper(clue);
for (int i = 0; i < upperedWord.Length; i++)
{
if (upperedWord[i] == clue)
{
foundSoFar[i] = originalWord[i];
}
}
HiddenWords[idx] = new string(foundSoFar);
Console.WriteLine(HiddenWords[idx]);
}
}
I have started learning c# just over 3 months so for homework I have an exercise where i have to read from a text file with 50 names and marks. I have to find the name with the highest mark display it and save the result to a text file.This is what I have come up with.
namespace FINAL
{
class Program
{
public static string [] parts;
struct StudentDetails
{
public string name;
public string surname;
};
struct CourseWorkResults
{ public int mark;
};
static void Main(string[] args)
{
string [] Lines = System.IO.File.ReadAllLines(#"F:\FINAL\StudentExamMarks.txt");
foreach (string line in Lines)
{
string[] parts = line.Split();
}
StudentDetails[] Student = new StudentDetails[50];
CourseWorkResults[] Results = new CourseWorkResults[50];
GetName( ref Student ,ref parts );
FindMark ( ref Results , parts);
FindMax (ref Results);
}
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
static void FindMark ( ref CourseWorkResults[]Results, string [] parts )
{
for (int i=0; i< Results.Length;i++)
{
Results[i].mark = Convert.ToInt16(parts[2]);
}
}
static void FindMax( ref CourseWorkResults[]Results)
{
for (int i = 0; i < Results.Length; i++)
{
int max = 0;
max = Results[2].mark;
if (Results[i].mark > max)
{
max = Results[i].mark;
}
}
}
static void DisplayResults( ref CourseWorkResults[]Results, StudentDetails[]Student, int max)
{
Console.WriteLine(" The student with the highest score is {0} {1} :{2}", Student[0].name, Student[1].surname, max);
}
}
}
My problem is the GetName procedure , I can't pass by reference parts. What am I doing wrong?
The problem here is that a struct is an immutable value type. So when you write :
Student[i].name = parts[0];
You are just trying to modify a local a copy of Student[i]. Actually, each time you trying to access Student[i], it will always return a copied value instead the instance on the list.
A workaround is to have StudentDetails as class instead of struct
class StudentDetails
{
public string name;
public string surname;
};
The issue applies also for CourseWorkResults struct.
In addition, as arrays are already reference in .NET. You don't really need to pass it as reference unless you want it to reference another object. I.e, this :
static void GetName(StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
will work as
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
Unless you add something like this:
static void GetName(ref StudentDetails[]Student, ref string[] parts)
{
Student = anotherStudentArray ; // Here the ref param is really needed as you want to reassign Student to a new array instance
for (int i = 0; i < Student.Length; i++ )
{
Student[i].name = parts[0];
Student[i].surname = parts[1];
}
}
Dear stackoverflow members,
I have this string:
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
I want to search for the values where the "keyword" is Position. In this case I want to get back 1 and 2. Each value is "indexed" with its own "keyword". So the value 1 in this string has the Position seperator. The value 1234 has the Article seperator and the value 4321 has the Quantity seperator.
I need a way to search through the string and want to get all positions, articles and quantitys back. Without the keywords.
Output shout be:
string[] position = {"1", "2"};
string[] article = {"1234", "4323"};
string[] quantity = {"4321", "3323"};
Hopefully some can help me here.
Thanks!
This is q quick solution I've come up with in LinqPad:
void Main()
{
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
var Articles = Indices(data, "Article").Dump("Articles: ");
var Posistions = Indices(data, "Position").Dump("Positions :");
var Quantities = Indices(data, "Quantity").Dump("Quantities :");
}
// Define other methods and classes here
public List<int> Indices(string source, string keyword)
{
var results = new List<int>();
//source: http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number
var temp = Regex.Split(source, "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)").ToList().Where (r => !String.IsNullOrEmpty(r)).ToList();
//select the list with index only where key word matches
var indices = temp.Select ((v,i) => new {index = i, value = v})
.Where (t => t.value == keyword);
foreach (var element in indices)
{
int val;
//get previous list entry based on index and parse it
if(Int32.TryParse(temp[element.index -1], out val))
{
results.Add(val);
}
}
return results;
}
Output:
Here's a possible algorithm:
Run trough the list and take each number / keyword.
Put them in a dictionary with key "keyword", value a list with all "numbers".
Iterate the dictionary and print they key + its values.
Below snippet can use to get the output like what you expected.
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
bool isDigit = false;
bool isChar = false;
Dictionary<int, string> dic = new Dictionary<int, string>();
int index = 0;
for (int i = 0; i < data.Length; i++)
{
if (char.IsNumber(data[i]))
{
isDigit = true;
if (isChar)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
index++;
isChar = false;
sb.Remove(0, sb.Length);
sbWord.Remove(0, sbWord.Length);
}
}
else
{
isDigit = false;
isChar = true;
sbWord.Append(data[i]);
}
if (isDigit)
sb.Append(data[i]);
if (i == data.Length - 1)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
}
}
List<string> Position = new List<string>();
List<string> Article = new List<string>();
List<string> Quantity = new List<string>();
if (dic.Count > 0)
{
for (int i = 0; i < dic.Count; i++)
{
if (dic[i].Split('|')[1] == "Position")
Position.Add(dic[i].Split('|')[0]);
else if (dic[i].Split('|')[1] == "Article")
Article.Add(dic[i].Split('|')[0]);
else
Quantity.Add(dic[i].Split('|')[0]);
}
}
string[] Position_array = Position.ToArray();
string[] Article_array = Article.ToArray();
string[] Quantity_array = Quantity.ToArray();
Try this simple solution.
class StrSplit{
public static void main(String args[]){
int i;
String str = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
String pattern= "(?<=Position)|(?<=Article)|(?<=Quantity)";
String[] parts = str.split(pattern);
List<String> Position = new ArrayList<String>();
List<String> Article = new ArrayList<String>();
List<String> Quantity = new ArrayList<String>();
for( i=0;i<parts.length;i++)
{
pattern="Position";
String[] subParts;
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Position.add(subParts[0]);
}
pattern="Article";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Article.add(subParts[0]);
}
pattern="Quantity";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Quantity.add(subParts[0]);
}
}
System.out.println("Position:");
for(i = 0; i < Position.size(); i++) {
System.out.println(Position.get(i));
}
System.out.println("Article:");
for(i = 0; i < Article.size(); i++) {
System.out.println(Article.get(i));
}
System.out.println("Quantity:");
for(i = 0; i < Quantity.size(); i++) {
System.out.println(Quantity.get(i));
}
}
}
Output:
Position:
1
2
Article:
1234
4323
Quantity:
4321
3323
I have my code to decrypt the string to numbers but i have the result
every time "-1-1-1"
protected void submit_Click(object sender, EventArgs e)
{
decryptScore(txtscore.Text);
}
public string decryptScore(string s)
{
string[] firstDigitArray = { "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
string[] secondDigitArray = { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
string[] thirdDigitArray = { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
string[] fourthDigitArray = { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
string[][] digitsArray = {firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray};
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i][i].IndexOf(d));
}
score.Text = decryptedScore;
return decryptedScore;
}
public string decryptScore(string s)
{
var firstDigitArray = new List<string>{ "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
var secondDigitArray = new List<string> { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
var thirdDigitArray = new List<string> { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
var fourthDigitArray = new List<string> { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
var digitsArray = new List<List<string>>{ firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray };
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i].FindIndex(x=>x==d));
}
return decryptedScore;
}
PS: Don't forget if scorelength is greater or equal to 4 you'll get an exception(since you only have 4 digitArrays)
In the line
decryptedScore += (digitsArray[i][i].IndexOf(d));
you are searching for a string a single string for a the value. You need to search the array.
Change this line to
decryptedScore += Array.IndexOf(digitsArray[i], d);
This will search the array for a particular value and return you it's index. As a result you will get the required number back.
Replace
decryptedScore += (digitsArray[i][i].IndexOf(d));
with
decryptedScore += Array.IndexOf(digitsArray[i], d);
I am pretty new to c# . Got a problem with command line arguments. what i want to do is make use of the third cmd line argument and write to it. I have specified the path of the file I want to write into and other stuffs. But the question here is can i access the command line arguments(for eg; args[3]) from user defined functions? How do we do tat? below is my code.
public class Nodes
{
public bool isVisited;
public string parent;
public string[] neighbour;
public int nodeValue;
public Nodes(string[] arr, int nodeValue)
{
this.neighbour = new string[arr.Length];
for (int x = 0; x < arr.Length; x++)
this.neighbour[x] = arr[x];//hi...works??
this.isVisited = false;
this.nodeValue = nodeValue;
}
}
public class DFS
{
static List<string> traversedList = new List<string>();
static List<string> parentList = new List<string>();
static BufferBlock<Object> buffer = new BufferBlock<object>();
static BufferBlock<Object> buffer1 = new BufferBlock<object>();
static BufferBlock<Object> buffer3 = new BufferBlock<object>();
static BufferBlock<Object> buffer2 = new BufferBlock<object>();
public static void Main(string[] args)
{
int N = 100;
int M = N * 4;
int P = N * 16;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<string> global_list = new List<string>();
StreamReader file = new StreamReader(args[2]);
string text = file.ReadToEnd();
string[] lines = text.Split('\n');
string[][] array1 = new string[lines.Length][];
Nodes[] dfsNodes = new Nodes[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Trim();
string[] words = lines[i].Split(' ');
array1[i] = new string[words.Length];
dfsNodes[i] = new Nodes(words, i);
for (int j = 0; j < words.Length; j++)
{
array1[i][j] = words[j];
}
}
StreamWriter sr = new StreamWriter(args[4]);
int startNode = int.Parse(args[3]);
if (args[1].Equals("a1"))
{
Console.WriteLine("algo 0");
buffer.Post(1);
dfs(dfsNodes, startNode, "root");
}
else if (args[1].Equals("a2"))
{
Console.WriteLine("algo 1");
buffer1.Post(1);
dfs1(dfsNodes, startNode, "root",sr);
}
else if (args[1].Equals("a3"))
{
buffer3.Post(1);
List<string> visitedtList = new List<string>();
Console.WriteLine("algo 2");
dfs2(dfsNodes, startNode, "root", visitedtList,sr);
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.ReadLine();
}
public static void dfs(Nodes[] node, int value, string parent,StreamWriter sr1)
{
int id = (int)buffer.Receive();
sr1=new StreamWriter(arg
Console.WriteLine("Node:" + value + " Parent:" + parent + " Id:" + id);
sr1.Write("Node:" + value + " Parent:" + parent + " Id:" + id);
id++;
traversedList.Add(value.ToString());
buffer.Post(id);
for (int z = 1; z < node[value].neighbour.Length; z++)
{
if (!traversedList.Contains(node[value].neighbour[z]))
{
dfs(node, int.Parse(node[value].neighbour[z]), value.ToString(),sr1);
}
}
return;
}
public static void dfs1(Nodes[] node, int value, string parent, StreamWriter sr)
{
int id = (int)buffer1.Receive();
sr.Write("Node:" + value + " Parent:" + parent + " Id:" + id);
node[value].isVisited = true;
node[value].parent = parent;
id++;
buffer1.Post(id);
for (int z = 1; z < node[value].neighbour.Length; z++)
{
buffer2.Post(node[int.Parse(node[value].neighbour[z])]);
if (!isVisited())
{
dfs1(node, int.Parse(node[value].neighbour[z]), value.ToString(),sr);
}
}
return;
}
public static void dfs2(Nodes[] node, int value, string parent, List<string> visitedtList, StreamWriter sr)
{
int id = (int)buffer3.Receive();
sr.Write("Node:" + value + " Parent:" + parent + " Id:" + id);
id++;
visitedtList.Add(value.ToString());
buffer3.Post(id);
for (int z = 1; z < node[value].neighbour.Length; z++)
{
buffer2.Post(node[int.Parse(node[value].neighbour[z])]);
if (!visitedtList.Contains(node[value].neighbour[z]))
dfs2(node, int.Parse(node[value].neighbour[z]), value.ToString(), visitedtList,sr);
}
return;
}
public static bool isVisited()
{
Nodes node = (Nodes)buffer2.Receive();
return node.isVisited;
}
}
So the thing is I want to write the output of each dfs to the file specified as the command line argument. So can I have access to the args in the dfs, dfs1 methods??? Thank you.
You could either keep a static field to hold it, or just use Environment.GetCommandLineArgs().
Well, in its simplest form, just save it to use later
class Program
{
static string _fpath;
static void Main(string[] args)
{
// ...stuff
_fpath = args[3];
}
static void WriteFile()
{
using(var stream = File.Open(_fpath, ...))
{
// write to file
}
}
}
Not necessarily exactly how I would do it, but you get the idea.
Also, regarding this bit of code...
this.neighbour = new string[arr.Length];
for (int x = 0; x < arr.Length; x++)
this.neighbour[x] = arr[x];//hi...works??
You can simply write
this.neighbour = arr;
Ahh, the wonders of managed code :D. No need to copy elements across to the second array. Of course, you need to consider the fact that changes to elements in the argument array (arr) will be reflected in your internal array now.
It would be better to pass arguments into functions instead of relying on some "hidden" way to pass them.
Both static variable and GetCommandLineArgs are useful to pass them in hidden way (as pointed out in other answers). Drawbacks are harder to test (since need to set static shared dependency) and less clear for future readers that there is this hidden dependency.