Cannot concat string in C# - c#

I have a code to read data block inside MIFARE card.
The method rfidM1.ReadDataFromCardM1 will read a block and return value in string.
string memQuery = string.Empty;
int i = 0, j = 0;
sector = 4;
block = 4;
for (i = 0; i < block; i++)
{
for (j = 0; j < sector; j++)
{
memQuery += rfidM1.ReadDataFromCardM1(Convert.ToByte(j), Convert.ToByte(i), _Key1) + ",";
}
}
My intention is concating memQuery with comma. Example output here:
,0,,,,,True,,C0-12320,0,,,,,,
I concat memQuery with various ways, for example, using +=, StringBuilder or ArrayList but they didn't work because it always has an output like this when I put it in MessageBox.
,0
It looks like string after that 0 cannot concat with other string after it. Why?

My intention is concating memQuery with comma
Wel, first get rid of the ArrayList and replace it with var memQuery = new List<string>();.
Inside your for-loops, decide what to with null or empty results. Add a null or skip the Add or ...
And then when the memQuery is filled correctly, you can do
string result = string.Join(",", memQuery);
string.Join() can handle nulls in the input sequence.

Related

I need to get a string Array with single lines, which should be extraced from a big text with paragraphs

I got an idea that i wanted to make today but ran into the problem that i have a string variable with paragraph, but i need an Array of single lines. So I tried to do this with the String.Substring and the String.IndexOf functions but this only worked kinda because i dont exactly know how VisualStudio handels the Index of Paragraphs and how strings work with paragraphs because i just learned C# this year.
I tried it in Windows-Forms btw.
Can anyone tell me how index's with paragraphs work or especialy how to use them correctly.
This is the code i tried which only works for the 1st line and works kinda with the 2nd but not with any further
string input_raw;
string[] input = new string[100];
int index_zeile = 0;
int x = 0, y = 0;
input_raw = input_text_box.Text;
for (int i = 0; i < 100; i++)
{
if (i == 0)
{
y = input_raw.IndexOf(";");
input[i] = input_raw.Substring(index_zeile, y);
x = y + 1;
}
else
{
index_zeile = input_raw.IndexOf(";", x);
input[i] = input_raw.Substring(x, index_zeile-3);
x = x + index_zeile;
}
}
I wish you entered your text input, but you can split the string into an array. The following code assigns a multi-line string to an array.
string[] lines = input_text_box.Text.Split('\n');

How to include two text boxes texts?

I want to include two text box texts to one text box like this
both of them are multiline.
But I want special form of include, in other words I want to include them like this
textbox 1 texts: '' help''' '' other''
textbox 2 texts:' 1' '2' '' 3''
results: help1 _ help2 _ help3
other1_other2_other3
Multiline textboxes return a string array with the lines in the Lines property. You could do something like this
string[] words = textBox1.Lines;
string[] numbers = textBox2.Lines;
var resultLines = new string[words.Length];
var sb = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
sb.Length = 0; // Reset StringBuilder for the next line.
for (int j = 0; j < numbers.Length; j++) {
sb.Append(words[i]).Append("-").Append(numbers[j]).Append("_");
}
if (sb.Length > 0) {
sb.Length--; // remove the last "_"
}
resultLines[i] = sb.ToString();
}
resultsTextBox.Lines = resultLines;
First we get the words and numbers arrays. Then we create a new array for the result. Since we want a result line for each word, we make it words.Length in size.
Then we loop through the words. We use a StringBuilder to build our new lines. This is more efficient as concatenation strings with +, as it minimizes copy operations and memory allocations.
In a nested loop we put the words and numbers together.
An elegant way to solve your issue is to make use of the String.Join method in C#. I'm adding this answer because I'm a big fan of the method and think it must be part of some answer to this question because it has to do with combining strings.
Here's the code that I'd use to solve the challenge:
string[] firstInput = textBox1.Lines;
string[] secondInput = textBox2.Lines;
var combinedInputs = new string[firstInput.Length];
var combinedLine = new string[secondInput.Length];
for(int i = 0; i < firstInput.Length; i++)
{
for(int j = 0; j < secondInput.Length; j++)
{
combinedLine[j] = firstInput[i] + secondInput[j];
}
//Combine all values of combinedLine with a '-' in between and add this to combinedInputs.
combinedInputs[i] = String.Join("-", combinedLine);
}
outputTextBox.Lines = combinedInputs; //the resulting output
I hope this answer helped aswell. And I'd like to give credits to Olivier for explaining the textbox part. Another thing that I'd like to add is that this answer isn't meant to be the most efficient, but is meant to be easy to read and understand.

Getting error while using split method for reading multiple integers in a single line

I am getting an error while using Split while reading an integer from the user
int[] a = new int[s];
for (i = 0; i < s; i++)
{
a[i] = Int32.Parse(Console.ReadLine().Split(' '));
}
Can you please help me how to use Split.
LINQ can really help you here:
int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Since split returns an array, and each time you need the i'ed one, you should change it like this:
int[] a = new int[s];
string[] input = Console.ReadLine().Split(' ');
for (i = 0; i < s; i++)
{
a[i] = Int32.Parse(input[i]);
}
You need to read the input only once btw.
Like #loneshark99 said it would be even better to use TryParse(). Since that returns a boolean, you can check if the input are indeed integers. If you just use Parse and they are not integers, it would throw an exception.
Code with TryParse():
int[] a = new int[s];
string[] input = Console.ReadLine().Split(' ');
for (i = 0; i < s; i++)
{
if (Int32.TryParse(input[i], out a[i]))
{
//successfully parsed
}
}
The if-statement is not necessary but it's just to point out how you could use the TryParse.
We can take the input as string first
string[] array_temp = Console.ReadLine().Split(' ');
and then convert the array into Int
int[] array = Array.ConvertAll(array_temp,Int32.Parse);

How to append every X in c# stringbuilder

I'm using unity and c# and am not sure how to use stringbuilder to append a "/" every X characters. I have code and can build a string from a array with the code below, and add a comma after each string, but i need to add the "/" after every x string
it should for example convert "122342" to "1,2,2,/,3,4,2". Currently it would convert it to "1,2,2,3,4,2"
this is the code i have already
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Use a FOR loop and then check if the character is a factor of some desired nTH character. If so add an extra '/'.
int x = 2; // your x
StringBuilder builtstring = new StringBuilder();
for (int i = 0; i < tobuild.Length; i++)
{
string item = tobuild[i];
builtstring.Append(item).Append(",");
if (i%x==0) { builtstring.Append("/"); }
}
string built = builtstring.ToString();
Add an if statement to evaluate the character and then act accordingly.
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(griditem == 'x') { Builtstring.Append(griditem).Append(#"/"); }
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Or if you actually want to count a certain number of characters before putting a slash you can do this.
int count = 10;
int position = 0;
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(position == count) { Builtstring.Append(griditem).Append(#"/"); position = 0; }
else{Builtstring.Append(griditem).Append(","); position++;}}
built = Builtstring.ToString();
You can iterate over the array of strings using a for loop, which provides an index.
For each iteration, add the current String to the StringBuilder, in addition to a ',' in case we still didn't reach the last string in the array.
Also, after x strings add a '/'. We can know that we reached x strings using the % (modulus) operator.
Notice that I start the loop from index = 1. I do that because the modulus operator for the value 0 with any positive number will yield 0, which will add the '/' char after the first word, something that we don't necessarily want.
static void Insert(StringBuilder b, int x, string[] tobuild)
{
for(var index = 1; index < tobuild.Length; ++index)
{
b.Append(tobuild[index]);
if(index != tobuild.Length -1)
{
b.Append(",");
}
if(0 == index % x)
{
b.Append("/");
}
}
}

Split and remove duplicate from String

I want to split the given string and remove the duplicate from that string. Like I have following string:
This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question.
Now I want to split that whole string with white space and that new array will did not have duplicate entry.
How can I do this?
"This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question."
.Split() // splits using all white space characters as delimiters
.Where(x => x != string.Empty) // removes an empty string if present (caused by multiple spaces next to each other)
.Distinct() // removes duplicates
Distinct() and Where() are LINQ extension methods, so you must have using System.Linq; in your source file.
The above code will return an instance of IEnumerable<string>. You should be able to perform most operations required using this. If you really need an array, you can append .ToArray() to the statement.
add the array into a HashSet<String>, this would remove the duplicates.
here is Micorosft documentation on HashSet..
static void Main()
{
string str = "abcdaefgheijklimnop";
char[] charArr = str.ToCharArray();
int lastIdx = 0;
for (int i = 0; i < str.Length;)
{
for (int j = i + 1; j < str.Length - 1; j++)
{
if (charArr[i] == charArr[j])
{
//Console.WriteLine(charArr[i]);
int idx = i != 0 ? i - 1 : i;
lastIdx = j;
string temp = str.Substring(idx, j - idx);
Console.WriteLine(temp);
break;
}
}
i++;
}
Console.WriteLine(str.Substring(lastIdx));
}

Categories

Resources