How can I add additional 30 character from the char that matches where in my code below.
private void CheckGarbageCharacters(string input)
{
var contentList = File.ReadAllLines(input).ToList();
int[] lineno = { 0 };
foreach (var line in contentList)
{
lineno[0]++;
foreach (var errorModel in from c in line
where c > '\u007F'
select new ErrorModel
{
Filename = Path.GetFileName(input),
LineNumber = lineno[0],
ErrorMessage = "Garbage character found.",
Text = c.ToString()
})
{
_errorList.Add(errorModel);
}
}
}
I'm not sure I fully understand your question but based on the code you have provided it seems like you are trying to do something like this...
~ Pseudo Code ~ This has not been tested ~
private void CheckGarbageCharacters(string filename)
{
var lines = File.ReadAllLines(filename).ToList();
for (int i = 0; i < lines.Count; i++)
{
var line = lines[i];
for (int j = 0; j < line.Length; j++)
{
var c = line[j];
if (c > '\u007F')
{
// Grab the next 30 characters after 'c'
var text = c.ToString();
for (int k = 0; k < 30; k++)
{
if ((j + k) > (line.Length - 1))
{
break;
}
text += line[j + k].ToString();
}
// Create the error message
var error = new ErrorModel()
{
Filename = Path.GetFileName(filename),
LineNumber = i,
ErrorMessage = "Garbage character found.",
Text = text
};
// Add the error to the list
_errorList.Add(error);
}
}
}
}
I'm not sure what you mean by "add additional 30 characters from the char that matches where in my code" though.
EDIT
I've updated my answer according to the information you've provided in the comments. I believe this is what you are trying to do here.
Related
I'm a bit out of practice and currently having a hard time with this one question.
If a character appears only once in the given string, I need to replace it with 'x' If a character appears several times in the string I need to replace it with 'y' (Case sensitive) e.g. "Passable" would return as "xyyyyxxx".
So far I've tried converting the string to a char array and comparing it to a copy of itself using nested loops, but I cant figure out a way to save the index of all occurrences to change them into x or y.
Unfortunately it didn't work out too great, and I'm sure there is a much simpler way of doing this that I'm missing, any ideas?
This is what I have so far:
for (int i = 0; i < OccuredArray.Length; i++)
{
for (int x = 0; x < CharArray.Length; x++)
{
if (CharArray[x] == OccuredArray[i])
{
TimesOccured++;
}
}
if (TimesOccured > 1)
{
for (int y = 0; y < OccuredArray.Length; y++)
{
if (OccuredArray[i] == OccuredArray[y])
{
OccuredArray[i] = 'y';
}
}
}
if (TimesOccured == 1)
{
for (int y = 0; y < OccuredArray.Length; y++)
{
if (OccuredArray[i] == OccuredArray[y])
{
OccuredArray[i] = 'x';
}
}
}
TimesOccured = 0;
}
What about simplifying it a bit? Use a Dictionary<char, int> to count the occurences:
string input = "Passable";
var charCounter = new Dictionary<char, int>();
foreach (char c in input)
{
charCounter.TryGetValue(c, out int count);
charCounter[c] = ++count;
}
string output = string.Concat(input.Select(c => charCounter[c] == 1 ? "x" : "y"));
If you wanted to use a loop then you could do it like this:
var text = "Passable";
var countsByChar = new Dictionary<char, int>();
foreach (var c in text)
{
if (!countsByChar.TryAdd(c,1))
{
countsByChar[c]++;
}
}
foreach (var c in countsByChar.Keys)
{
text = text.Replace(c,
countsByChar[c] == 1
? 'x'
: 'y');
}
Console.WriteLine(text);
You could use a LINQ query instead though:
var text = "Passable";
var countsByChar = text.GroupBy(c => c)
.ToDictionary(g => g.Key,
g => g.Count());
foreach (var c in countsByChar.Keys)
{
text = text.Replace(c,
countsByChar[c] == 1
? 'x'
: 'y');
}
Console.WriteLine(text);
Based on your code I modified and commented on some cases which you should check out:
// So, I suggest this is the input string.
var OccuredArray = "abbcdd";
// It is always better for the length to be in a variable and to be used in for loops.
var OccuredArrayLenght = OccuredArray.Length;
// Here we will fill the placeholders depending on their appearance.
var OccuredArrayResult = new char[OccuredArrayLenght];
// Here we will trace the occurrences in which each index corresponds to a char from the ASCII table.
var OccuredArrayCharMap = new bool[byte.MaxValue];
for (int CurrentCharIndex = 0; CurrentCharIndex < OccuredArrayLenght; CurrentCharIndex++)
{
var CurrentChar = OccuredArray[CurrentCharIndex];
// If we have processed this char, we continue with the next one
if (OccuredArrayCharMap[CurrentChar] == true)
{
continue;
}
var Placeholder = 'x';
// Then we will check all the characters, starting from the next index
for (int NextCharIndex = CurrentCharIndex + 1; NextCharIndex < OccuredArrayLenght; NextCharIndex++)
{
//if (CharArray[FollowingCharIndex] == OccuredArray[OccuredArrayCharIndex])
//{
// TimesOccured++;
//}
// If char occured twice then the placeholder is y and we can break here
if (OccuredArray[NextCharIndex] == CurrentChar)
{
Placeholder = 'y';
break;
}
}
//if (TimesOccured > 1)
//{
// for (int y = 0; y < OccuredArray.Length; y++)
// {
// if (OccuredArray[OccuredArrayCharIndex] == OccuredArray[y])
// {
// OccuredArray[OccuredArrayCharIndex] = 'y';
// }
// }
//}
//if (TimesOccured == 1)
//{
// for (int y = 0; y < OccuredArray.Length; y++)
// {
// if (OccuredArray[OccuredArrayCharIndex] == OccuredArray[y])
// {
// OccuredArray[OccuredArrayCharIndex] = 'x';
// }
// }
//}
//TimesOccured = 0;
// Here we fill ouer result array with coresponding placeholder at matched index.
for (int CharIndex = CurrentCharIndex; CharIndex < OccuredArrayLenght; CharIndex++)
{
if (OccuredArray[CharIndex] == CurrentChar)
{
OccuredArrayResult[CharIndex] = Placeholder;
}
}
// And at the end we say that this char was already replaced.
OccuredArrayCharMap[CurrentChar] = true;
}
var ResultString = new string(OccuredArrayResult);
Console.WriteLine(OccuredArray);
Console.WriteLine(ResultString);
For my problem I am experiencing today comes in the form of a string array. The goal of this assignment is to use Random with a seed value of 243 as a key to access a hidden message from 22 lines. Within these 22 lines are 5 letters that form a word. Here is 22 lines containing 60 characters in each line and the goal is to use the key to pick the 5 letters from each line.
String[] line = { "<?JRrP*h^vtVc^ppOZI#PCAa{ (n1>&VSf~59eI7Tn5We^77O/CEvgdq}gU0",
"G;t#o=#|^ZWV01`a-h{=Js>!z`_j!&7PB9nCgtfHZ:WtWk4e&#k5i7uV{$E/",
"]7zXf&4uA=n8!Sa08IIoKyc~:#d*T8FcOWjB?~QQ =Ch(S37UT>RYobbSz>#",
"w*A)v5gHh>p9vvVeUzvfmMT~tr)8s(nC`11Lz:qhjjN6c$Z ^T,W$VQqUB/#",
"+NSrOLhed*2;)$z#}=;t7FY?z6?e^?cX+nf;6me6Kt|TBpN ZNr7&9j t4c8",
"-N&E2X/:<_k0W$HpH${*f?M0K_Qp##F!)M){nVAu`4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decrypted = new String[22];
var randNum = new Random(243);
int i, k;
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[i] = Convert.ToString(currentLine[randNum.Next(0, 60)]);
}
}
printIt(decrypted);
Console.ReadLine();
}
static void printIt(string[] decrypted)
{
var build = new StringBuilder();
for (int h = 0; h < 22; h++)
{
build.Append(Convert.ToString(decrypted[h]));
}
Console.WriteLine(build);
The help I am looking for is to understand how I can store the 5 characters from each line successfully within the decrypted array.
I can gain the correct answer if I insert directly in my nested for loop the Console.WriteLine(decrypted[i]);
However, if I try to pull the same line anywhere after the for loop containing random, I only am able to pull the first letter of each line.
Change your loop to:
String[] decrypted = new String[110];
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[k + i * 5] = Convert.ToString(currentLine[randNum.Next(0, 60)]);
}
}
And Print:
static void printIt(string[] decrypted)
{
var build = new StringBuilder();
for (int h = 0; h < decrypted.Length; h++)
{
build.Append(Convert.ToString(decrypted[h]));
}
Console.WriteLine(build);
}
I was able to solve my own problem after doing a bit more research and deduction of what I could possibly be missing. Here is the solution.
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[i] = decrypted[i] + Convert.ToString(currentLine[randNum.Next(0, 60)]);
//Adding the previous character to the new character to help build up the string.
}
It was after I realized I wasn't building up the characters properly I chose to add the previous character and it solved my problem.
I have a string[] with values like
string[] s = { "saravanan", "Karthick", "Jackson", "saravanan" };
I want to see below output
saravanan occures 2 times
Karthick occures 1 times
Jackson occures 1 times
How can I do this without using List or Dictionary
This is what I have tried so far:
int i, j;
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"}
Console.WriteLine("Number of Times occured Each Values");
for (i = 0; i < s.Length; i++)
{
int count = 0;
for (j = 0; j < s.Length; j++)
{
if (s[i] == (s[j]))
{
count++;
}
}
Console.WriteLine(s[i]+"is count="+count);
}
That code produces this output:
Number of Times occured Each Values
saravananis count=2
Karthickis count=1
Jacksonis count=1
saravananis count=2
Usually, we solve such problems (querying) via Linq
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
var result = string.Join(Environment.NewLine, s
.GroupBy(item => item)
.Select(chunk => $"{chunk.Key} occures {chunk.Count()} times"));
Console.Write(result);
In case of nested loops (your current code) we should not print out the same name several times. Let's introduce bool appeared if name has been appeared before
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
for (i = 0; i < s.Length; i++) {
int count = 0;
bool appeared = false;
for (j = 0; j < s.Length; j++) {
if (s[i] == (s[j])) {
// Names are same. Do we have the name before?
if (j < i) {
// If yes we have no need to loop any more
appeared = true;
break;
}
count++;
}
}
// if name has been appeared already we shouldn't print it out
if (!appeared)
Console.WriteLine(s[i] + "is count=" + count);
}
Since you don't want "saravanan" to appear twice in your output. Then you could use an empty string as a sentinel value. When you find matches that increase the count, blank out that element and have checks in place to skip the element when you run across it later.
using System;
public class Program
{
public static void Main()
{
string[] s = { "saravanan","KArthick","Jackson","saravanan" };
for (int i = 0; i < s.Length; i++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < s.Length; j++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
if (s[i] == s[j])
{
count++;
// Clear the element to indicate the element as already been counted
s[j] = string.Empty;
}
}
Console.WriteLine("{0} occurs {1} times", s[i], count);
}
}
}
Result
saravanan occurs 2 times
KArthick occurs 1 times
Jackson occurs 1 times
Fiddle Demo
you can use linq group option like this:
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"};
Console.WriteLine("Number of Times occured Each Values");
var groupArray = s.GroupBy(x => x);
foreach (var group in groupArray)
{
Console.WriteLine(group.Key + "is count=" + group.Count());
}
I have a section in my code that I run to check to see if the item is an spanish item or english item. I am using this logic from an old vb.net application.
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 1; i <= 15; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 16;
}
}
return k;
}
The following code loops around
then I get this error message :
ex.Message "Index and length must refer to a location within the
string.\r\nParameter name: length" string
please help!!!
You always go from 1 to 15 - if the (trimmed) text of TxtItem.Text is shorter then 15 chars you'll get the exception.
You should use the length-2 of sp_item as upper bound to avoid the error.
Also, instead of setting i = 16 you should use break to stop the for loop.
However, I think your algorithm could also be written like this instead of the for loop:
if (sp_item.IndexOf("XX")>=1) {
k=1;
}
In c# the first position is at index 0 not 1 like vb
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 0; i < sp_item.len-2; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 15;
}
}
return k;
}
you can use
if (sp_item.IndexOf("XX")>=0) {
k=1;
}
how to normalize the complex numbers in c#?when i have saved the text file of complex number in notepad.then i want to use these complex numbers in my c# code.And can be read text file of complex number in c#?
Current code used:
using (TextReader reader = File.OpenText("a.txt"))
{
var lineCount1 = File.ReadLines("a.txt").Count();
x1 = new double[lineCount1, 512];
for (int i = 0; i < lineCount1; i++)
{
for (int j = 0; j < 512; j++)
{
string line = reader.ReadLine();
string[] bits = line.Split(' ');
x1[i, j] = double.Parse(bits[j]);
}
}
}
its not working.!!! error in last line.
Perhaps you should have something like this:
static void Main(string[] args)
{
var lines = File.ReadAllLines("a.txt");
var complexes = new Complex[lines.Length];
for (int i = 0; i < complexes.Length; i++)
{
complexes[i] = Parse(lines[i]);
}
}
private static Complex Parse(string s)
{
var split = s.Split(new char[' '], StringSplitOptions.RemoveEmptyEntries); // I guess string is something like "12 54". If you have "12 + 54i" you'l get an exception here
return new Complex(double.Parse(split[0]), double.Parse(split[1]));
}