Start the index from zero - c#

I'm having trouble in this program, which is written to convert Unicode characters to 32-bit format; in the index section that started from zero.
Does the index need to start from zero?
Why can not it start from number 1? Please explain this part well.
int a;
textBox2.Text = " ";
for (int i = 0; i < textBox1.Text.Length; i++)
{
a = Char.ConvertToUtf32(textBox1.Text.Substring(i, 1), 0);
textBox2.Text = a.ToString();
if (textBox1.Text == " ")
{
textBox2.Text = " " ;
}
}

A string is similar to an array, and indexes in c# start from 0 for any array type. As for your code's efficiency, you can also move the if check inside the loop, to outside, as it is independent of any index. See the sample code below:
/// <param name="source"> equivalent to TextBox1.Text in original post</param>
public static int[] ConvertToUtf32(string source)
{
int[] result = new int[source.Length]; //equivalent to all the chars displayed in TextBox2.Text in original post
if (source.Equals(" "))
{
result[0] = ' ';
}
else
{
for (int i = 0; i < source.Length; i++)
{
result[i] = Char.ConvertToUtf32(source.Substring(i, 1), 0);
}
}
return result;
}

Related

Unable to find long string in array string - C#

I'm trying to find a long string in another string. For this I've been using G[i].Contains(P[arr]) but for some reason the code just skips that condition. In my case : G[I] is 1000 character long and P[arr] is 475. When I debug I can see strings are not trimmed and also I have verified that P[ARR] is part of G[I] in Notepad++ so it should definitely satisfy a condition.
for (int arr = 0; arr < P.Length; arr++)
{
for (int i = a; i < G.Length; i++)
{
if (G[i].Contains(P[arr]))
{
if (!(b == 0))
{
a = i + 1;
continue;
}
primary_1 = (a == 0) ? G[i].IndexOf(P[arr]) : primary;
++count;
a = i + 1;
Console.WriteLine("Counter: " + i);
break;
}
}
}

How to print occurrence of a character in string in alphabetical order in C#?

Can anyone help me to find most efficient way to print character occurrence along with that character in a given string in alphabetical order?
I am able to count occurrence of character in string but I am not able to sort it in alphabetical order.
string OutputString = string.Empty;
int count = 1;
char[] charArr = inputString.ToCharArray();
for (int i = 0; i < charArr.Length; i++) {
for (int j = i + 1; j < charArr.Length; j++) {
if (charArr[i] == charArr[j])
count++;
}
if (!OutputString.Contains(charArr[i]))
OutputString += charArr[i].ToString() + count.ToString();
count = 1;
}
OutputString = string.Concat(OutputString.OrderBy(c => c));
let's say input string in xgdgyd
output should be:
d2g2x1y1.
You can use Linq to simplify this:
string s = "xgdgyd";
var result = s
.GroupBy(c => c)
.Select(g => g.Key.ToString() + g.Count())
.OrderBy(x => x);
Console.WriteLine(string.Concat(result)); // Outputs "d2g2x1y1"
The most useful thing here is GroupBy(), which will group all identical items together. That allows us to use g.Count() to count the number of items in each group.
Then we just concatenate each group key (a char) with its count into a single string.
Example on .Net Fiddle.
(I've simplified the code to use string.Concat() rather than string.Join() here.)
Solution given by #Matthew with LINQ is perfect, but if you want a solution with for loops as you posted in question then do this.
sort inputString first, and remove the line of code that sorts OutputString at the end, like this::
string inputString = "xgdgyd";
inputString = string.Concat(inputString.OrderBy(c => c));
string OutputString = string.Empty;
int count = 1;
char[] charArr = inputString.ToCharArray();
for (int i = 0; i < charArr.Length; i++)
{
for (int j = i + 1; j < charArr.Length; j++)
{
if (charArr[i] == charArr[j])
count++;
}
if (!OutputString.Contains(charArr[i]))
OutputString += charArr[i].ToString() + count.ToString();
count = 1;
}
Since you might not yet know LINQ, here is a solution using "classic" techniques:
string input = "xgdgyd";
char[] charArr = input.ToCharArray();
Array.Sort(charArr); // Sort before counting as Gian Paolo suggests!
// ==> "ddggxy"
int count;
string output = "";
for (int i = 0; i < charArr.Length; i += count) { // Increment by count to get
// the next different char!
count = 1;
// Note that we can combine the conditions within the for-statement
for (int j = i + 1; j < charArr.Length && charArr[j] == charArr[i]; j++) {
count++;
}
output += charArr[i] + count.ToString();
}
Console.WriteLine(output); // ==> d2g2x1y1
Note that the increment i += count, which is equivalent to i = i + count is performed at the end of the for-loop. Therefore count will be initialized at this point.
Another variant that uses only one loop instead of two nested loops appends the previous character to the output and resets the counter as soon as a different character is found.
string input = "xgdgyd";
char[] charArr = input.ToCharArray();
Array.Sort(charArr); // Sort before counting as Gian Paolo suggests!
int count = 1;
string output = "";
for (int i = 1; i < charArr.Length; i++) {
if (charArr[i] == charArr[i - 1]) {
count++;
} else {
output += charArr[i - 1] + count.ToString();
count = 1;
}
}
// Output last char
output += charArr[charArr.Length - 1] + count.ToString();
Console.WriteLine(output);
A more advanced technique would be to use a StringBuilder. See Concatenating Strings Efficiently by Jon Skeet.

How to delete an element of an array?

I know this topic name is similar to another topic but that topic doesn't have the answers i wanted, so...
1st Question:
Let me say i have an array of:
string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
test[x] = "#" + (x + 1) + " element";
Console.WriteLine(test[x]);
}
/*
output:
#1 element
#2 element
#3 element
#4 element
#5 element
*/
and say i wanted to remove "#4 element" from the string array, so that it instead outputs:
/*
output:
#1 element
#2 element
#3 element
#5 element
*/
how do i do that?
[PS:]The Answer i'm looking for is something that's easy to understand for a beginner.
If you want to delete at particular index you can do as :
int[] numbers = { 1,2,3,4,5};
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(4);
numbers = tmp.ToArray();
But In your case since you are just expecting the element to be invisible and having the array length same :
string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
if(x!=3){
test[x] = "#" + (x + 1) + " element";
Console.WriteLine(test[x]);}
}
You cant just delete an Element from an array, you only can set it to "" for example.
Use List<string> instead.
1st Ans:
You can use list or if you dont want to use list use Linq but it will create a different memory location for array and will store elements there(I suppose).
You can implement linq on your array as below:
test = test.Where(x => !x.Equals("#4 element")).ToArray();
//Print test Now
and now test array does not have "#4 element".
2nd Ans
Instead of Console.WriteLine use Console.Write .
Use List<string> rather than an array.
Use list.RemoveAt(3) to remove the forth element (elements start at 0)
So you might end up with something like the following in order to achieve you desired output:
var test = new List<string>();
for (var x = 1; x <= 5; x++)
{
test.Add(String.Format("#{0} element", x));
}
Console.WriteLine(String.Join(" ", test);
test.RemoveAt(3);
Console.WriteLine(String.Join(" ", test);
Which will give you your desired output of:
#1 element #2 element #3 element #4 element #5 element
#1 element #2 element #3 element #5 element
For your edit. While flushing your o/p just do not flush the outdated element. Using some conditional operator.
Eg: 1. If you want to remove on the basis of array valve then use
string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
test[x] = "#" + (x + 1) + " element";
If (test[x] == "Desired value which you dont want to show")
Console.WriteLine(test[x]);
}
If you want to remove on the basis of array position then use
string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
test[x] = "#" + (x + 1) + " element";
If (x == "Desired index which you dont want to show")
Console.WriteLine(test[x]);
}
While what the others wrote is correct, sometimes you have an array, and you don't want to have a List<>...
public static void Main()
{
string[] test = new string[5];
for(int x = 0; x < test.Length; x++)
{
test[x] = "#" + (x + 1) + " element";
Console.WriteLine(test[x]);
}
Console.WriteLine();
RemoveAt(ref test, 3);
// Or RemoveRange(ref test, 3, 1);
for(int x = 0; x < test.Length; x++)
{
Console.WriteLine(test[x]);
}
}
public static void RemoveAt<T>(ref T[] array, int index)
{
RemoveRange(ref array, index, 1);
}
public static void RemoveRange<T>(ref T[] array, int start, int count)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (start < 0 || start > array.Length)
{
throw new ArgumentOutOfRangeException("start");
}
if (count < 0 || start + count > array.Length)
{
throw new ArgumentOutOfRangeException("count");
}
if (count == 0)
{
return;
}
T[] orig = array;
array = new T[orig.Length - count];
Array.Copy(orig, 0, array, 0, start);
Array.Copy(orig, start + count, array, start, array.Length - start);
}
Two simple methods to remove elements of an array (RemoveAt and RemoveRange), with full example of use.
Arrays have fixed size, so if you want add or remove element from them you need to deal with resizing. Therefore in C# it is recommended to use Lists instead (they deal with it themselves).Here is nice post about Arrays vs Lists.
But if you really want to do it with Array or have a reason for that, you could do it this way:
class Program
{
static void Main(string[] args)
{
int[] myArray = { 1, 2, 3, 4, 5 };
//destination array
int[] newArray = new int[myArray.Length-1];
//index of the element you want to delete
var index = 3;
//get and copy first 3 elements
Array.Copy(myArray, newArray, index);
//get and copy remaining elements without the 4th
Array.Copy(myArray, index + 1, newArray, index, myArray.Length-(index+1));
//Output newArray
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < newArray.Length; i++)
{
sb.Append(String.Format("#{0} {1}", i + 1, newArray[i]));
if (!(i == newArray.Length - 1))
{
sb.Append(", ");
}
}
Console.Write(sb.ToString());
Console.ReadLine();
}
See My solution... let me know if does helps...
class Program
{
// this program will work only if you have distinct elements in your array
static void Main(string[] args)
{
string[] test = new string[5];
for (int x = 0; x <= test.Length - 1; x++)
{
test[x] = "#" + (x + 1) + " element";
Console.WriteLine(test[x]);
}
Console.ReadKey();
Program p = new Program();
test = p.DeleteKey(test, "#3 element"); // pass the array and record to be deleted
for (int x = 0; x <= test.Length - 1; x++)
{
Console.WriteLine(test[x]);
}
Console.ReadKey();
}
public string[] DeleteKey(string[] arr, string str)
{
int keyIndex = 0;
if (arr.Contains(str))
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] == str)
{
keyIndex = i; // get the index position of string key
break; // break if index found, no need to search items for further
}
}
for (int i = keyIndex; i <= arr.Length - 2; i++)
{
arr[i] = arr[i+1]; // swap next elements till end of the array
}
arr[arr.Length - 1] = null; // set last element to null
return arr; // return array
}
else
{
return null;
}
}
}

c# number sequence

I have made this code to get from 2a3b to aabbb. This also has to apply when no numbers are given. Like aa2b => aabb.
The program is fully working but my problem is, it takes in alot of space. I think it is my split but my array will be like this if the input is 2a2b:
2
NULL
NULL
a
2
NULL
NULL
b
Does someone know what i'm doing wrong? Is it my split?
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
string[] array = new string[20];
int count = 1;
array = Regex.Split(value, "(\\d{0,2})");
while (count < array.Length)
{
int num;
if (array[count] != "")
{
bool isNumeric = int.TryParse(array[count], out num);
if (!isNumeric)
{
test = test + string.fill(array[count], intNumber);
test = test + array[count];
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
count++;
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
How about using a simple Regex.Replace?
string input = "2a3bcccc";
string output = Regex.Replace(
input,
#"(\d+)(\w)",
m => new String(m.Groups[2].Value[0],int.Parse(m.Groups[1].Value)));
result : aabbbcccc
A simpler way to resolve your problem is to get rid of regex, the array creation would be like:
char[] array = value.ToArray();
The code, with the minor corrections due to the array and some improvements being a char array (intead of a string array):
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
foreach (char c in value.ToArray())
{
int num;
bool isNumeric = int.TryParse(c.ToString(), out num);
if (!isNumeric)
{
test = test + new string(c, intNumber);
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
}
Quick test program works like a charm without using a regex.
const string value = "aa2b";
var result = "";
for (var i = 0; i < value.Length; i++)
{
int num;
if (Int32.TryParse(value.Substring(i, 1), out num))
{
for (var j = 0; j < num; j++)
{
result += value.Substring(i + 1, 1);
}
i++;
}
else
{
result += value.Substring(i, 1);
}
}
textBox1.AppendText("woord:" + result);
I generally try to avoid Regex, unless there is a complex pattern I need to verify.
Here is my solution to your problem:
string k = Console.ReadLine();
string t = "";
int count = 0, next;
for (int i = 0; i < k.Length; i++)
{
while (int.TryParse(k[i].ToString(), out next)) // Find the count of the next letter
{
count = count * 10 + next; // If count had a 2, and the next character is 3 (means we need to calculate 23), simply multiply the previous count by 10, and add the new digit
i++; // Move to the next character
}
t += new String(k[i], count > 0 ? count : 1); // Add the new sequence of letters to our string
count = 0; // Clear the current count
}
Console.WriteLine(t);
You can optimize the above, by using the StringBuilder class, but I think it's enough to understand the general solution first, rather than trying to find optimizations.

ArgumentOutOfRange exception C#

I am doing my homework and I have to do a program that extends simple letters from a file, like E and F, to continuous productions, given also in the folder, such as E+T E-F etc. Anyway the code shown below gives me an argument out of range exception. I crafted the same code in java and all works fine. I don't know why in C# it gives me this exception. Please give me some advice!!
I forgot to put the file that I'm reading from:
EFT
a+()
E
E+T|E-T|T
T*F|T/F|F
a|(E)
public void generare(){
String N = null;
String T = null;
String S = null;
String[] P = null;
TextReader tr = new StreamReader("dateIntrare.txt");
try
{
N = tr.ReadLine();
T = tr.ReadLine();
S = tr.ReadLine();
P = new String[N.Length];
for (int i = 0; i < N.Length; i++)
{
P[i] = tr.ReadLine();
}
tr.Close();
Console.WriteLine("Neterminale: N = " + N);
Console.WriteLine("Terminale: T = " + T);
Console.WriteLine("Productii ");
for (int i = 0; i < P.Length; i++)
Console.WriteLine("\t" + P[i]);
Console.WriteLine("Start: S = " + S);
Boolean gata = false;
String iesire = S.Substring(0, S.Length);
Console.WriteLine("\nRezultat");
Console.Write("\t");
while ((gata == false) && (iesire.Length < 50))
{
Console.Write(iesire);
Boolean ok = false;
for (int i = iesire.Length - 1; i >= 0 && ok == false; i--)
{
for (int j = 0; j < N.Length && ok == false; j++)
if (N[j] == iesire[i])
{
String s1 = iesire.Substring(0, i);
String s2 = iesire.Substring(i + 1, iesire.Length); // HERE IS THE EXCEPTION TAKING PLACE
String inlocuire = P[N.IndexOf(iesire[i])];
String[] optiuni = null;
String[] st = inlocuire.Split('|');
int k = 0;
foreach (String now in st)
{
k++;
}
optiuni = new String[k];
st = inlocuire.Split('|');
k = 0;
foreach (string next in st)
{
optiuni[k++] = next;
}
Random rand = new Random();
int randNr = rand.Next(optiuni.Length);
String inlocuireRandom = optiuni[randNr];
iesire = s1 + inlocuireRandom + s2;
ok = true;
}
}
if (ok == false)
{
gata = true;
}
else
{
if (iesire.Length < 50)
Console.Write(" => ");
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("Eroare, fisierul nu exista!");
}
Console.WriteLine();
}
But why in java works and here not? I'm confused
When in doubt, read the documentation. In Java, the 2-parameter overload of substring takes a start index and an end index. In .NET, the second parameter is the number of characters to take, not an end index.
So you probably want
String s2 = iesire.Substring(i + 1, iesire.Length - i - 1);
Or to be simpler about it, just use the 1-parameter version, which takes all the characters from the specified index onwards:
String s2 = iesire.Substring(i + 1);
(I'd use that in Java too...)
Fundamentally though, it's worth taking a step back and working out why you couldn't work this out for yourself... even if you missed it before:
Look at the line that threw the exception in your code
Look at which method actually threw the exception (String.Substring in this case)
Look at the exception message carefully (it's a really good hint!) and also any nested exceptins
Read the documentation for the relevant method carefully, especially the sections describing the parameters and exceptions
This is a common mistake while porting codes from Java to c#.
Substring in Java takes start & end parameters but in c# they are start and length

Categories

Resources