I encountered out of range exception during a substring operation.
My string's length is 100, and the position of substrings are 58 and 94, which should not have given an out of range exception.
Below are the logs and code:
string parameters = item.GetFormattedValue("Parameters").ToString();
Console.WriteLine("parameters = " + parameters.ToString());
Console.WriteLine("parameters length: " + parameters.Length);
Console.ReadKey();
int p1 = parameters.IndexOf(#">");
Console.WriteLine("p1 = " + p1);
int p2 = parameters.IndexOf(#"<", parameters.IndexOf(#"<") + 1);
Console.WriteLine("p2 = " + p2);
Console.ReadKey();
string parametersSub = parameters.Substring(p1, p2);
Console.WriteLine("parametersSub: " + parametersSub);
Console.ReadKey();
The second argument in Substring is the length of the string to select, rather than the index to select up to.
Since your arguments are 58 and 94, you are trying to select from index 58 for 94 characters which goes outside the length of your string.
To select between the two indices, get the difference between the two and use that for the length to select:
int p1 = parameters.IndexOf(#">");
Console.WriteLine("p1 = " + p1);
int p2 = parameters.IndexOf(#"<", parameters.IndexOf(#"<") + 1);
Console.WriteLine("p2 = " + p2);
Console.ReadKey();
string parametersSub = parameters.Substring(p1, p2 - p1);
Console.WriteLine("parametersSub: " + parametersSub);
Of course, you should still check that both the start index, and length are within the bounds of the string.
Related
I made [Hashtable hash] such as
hash(i, 1)
hash(j, 2)
Also I made an [arraylist sArray] which include "i" or "j" such as
sArray[0] : hello
sArray[1] : first number is i
sArray[2] : second number is j
sArray[3] : bye
Now, I want to change the "i" and "j" in the sArray to the values of the hash.
How can I do it?
If I understand properly, I think this is the code in c#
//Your example
int i = 1;
int j = 2;
var hash = new System.Collections.Hashtable();
hash[i] = -173.5;
hash[j] = 37;
var sArray = new System.Collections.ArrayList();
sArray.Add("hello");
sArray.Add("first number is " + hash[i].ToString());
sArray.Add("second number is " + hash[j].ToString());
sArray.Add("bye");
// more general, you could have different i and j position
i = 3;
j = 4;
hash[i] = 33.3;
hash[j] = -44.4;
sArray[1] = "number in " + i.ToString() + " position is " + hash[i].ToString();
sArray[2] = "number in " + j.ToString() + " position is " + hash[j].ToString();
// I think following option is more easy to read and fast if iterated
i = 5;
j = 6;
hash[i] = 55.5;
hash[j] = -66.6;
sArray[1] = String.Format("number in {0} position is {1}", i, hash[i]);
sArray[2] = String.Format("number in {0} position is {1}", j, hash[j]);
I am trying to make a console application for my programming class. The if statement is not working correctly. I want it to count the string length and if it's greater than 10000 or less than 0, go to the else statement. But it doesn't and continues the if statement.
static void Main(string[] args)
{
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
if (a.Length <= MaxLength && a.Length >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
You have to use int.Parse(a).
if (int.Parse(a) <= MaxLength && int.Parse(a) >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Your code is checking the length of the string input - so if a user enters, for example, 100 the length will be three.
A length of a string can never be less than zero, and I very much doubt it will ever be longer than 10000.
Perhaps what you were actually trying to do is convert the user's entry to a number, while also keeping th ability to use the Substring method from the users input as a set of characters.
In which case, you want 2 variables
The original user input (a string, where you can use Substring) - a from your original code
A numerical representation of the input for which you can compare to a min & max number. val in the code below
Another consideration is that the user may enter a value which is not convertable to a number, so
A boolean indicating that the user has entered a valid number. isValidEntry in the code below
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
int val = 0;
bool isValidEntry = int.TryParse(a, out val);
if (isValidEntry && val <= MaxLength && val >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
I believe there is some confusion on what you are doing. Your description says you are trying to count the amount of characters in the inputed string. In which case you will need a string with more that 10000 characters to go the else statement.
However your program code claims you just want the numerical value of your string. Therefore you should try using a conversion method.
int x = int.Parse(a);
Obviously you need to do bound checking on x instead of a afterwards.
I'm trying to make a roulette command for my bot, and this is what I got so far.
if (!String.IsNullOrEmpty(e.Data.Message.Replace("!roulette", ""))) {
string _u = e.Data.Nick;
string _b = e.Data.Message.Replace("!roulette", "");
string[] _c = { "R", "B", "G", "Red", "Black", "Green",
"r", "b", "g", "redblack green" };
Random _r = new Random();
int rnum = _r.Next(0, 36); // 0-35
if (_b.Contains(rnum.ToString()) && _b.Contains(_c.ToString())) {
MessageHandler(conf.Nick, e.Data.Nick + " spins the wheel.. " + _b.ToString() + " " + (string)_c[rnum] + "! We have a winner!", 8);
} else {
MessageHandler(conf.Nick, e.Data.Nick + " spins the wheel.. " + rnum.ToString() + " " + (string)_c[rnum] + "! You lose!", 8);
}
}
I get the Index outside the bounds of the array. error, it's very strange for something not so complicated.
How would I fix this, would I ignore the array and go for a Dictionary or List<>?
You are referencing _c array's element using the index rnum: _c[rnum].
Thernum variable can have any integer value from the range 0 - 35.
But the _c array has only 10 elements.
To fix it, limit the rnum variable to the range 0 - 9:
int rnum = _r.Next(0, 10);
I'm totally puzzled
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
I would expect: 7*3=21
But then I receive: 55*51=2805
That is the ASCII value for the character 7 and 3. If you want number representation then you can convert each character to string and then use Convert.ToString:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
55 and 51 are their locations in the ascii chart.
Link to chart - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
try using int.parse
This works:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
You have to do ToString() to get the actual string representation.
You are getting the ASCII codes for 7 and 3, which are 55 and 51 respectively.
Use int.Parse() to convert a char or string to a value.
int tempc0 = int.Parse(temp[0].ToString());
int tempc1 = int.Parse(temp[1].ToString());
int product = tempc0 * tempc1; // 7 * 3 = 21
int.Parse() doesn't accept a char as a parameter, so you have to convert to string first, or use temp.SubString(0, 1) instead.
This works, and is more computationally efficient than using either int.Parse() or Convert.ToInt32():
string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
Converting a character to an integer gives you the Unicode character code. If you convert a string to integer it will be parsed as a number:
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));
When you write string temp = "73", your temp[0] and temp[1] are being char values.
From Convert.ToInt32 Method(Char) method
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
That means converting a char to an int32 gives you the unicode character code.
You just need to use .ToString() method your your temp[0] and temp[1] values. Like;
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
Here is a DEMO.
I want to get the ASCII value of characters in a string in C#.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
How can I get ASCII values in C#?
From MSDN
string value = "9quali52ty3";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
You now have an array of the ASCII value of the bytes. I got the following:
57
113
117
97
108
105
53
50
116
121
51
string s = "9quali52ty3";
foreach(char c in s)
{
Console.WriteLine((int)c);
}
This should work:
string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
Console.WriteLine(b);
}
Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.
string s = "9quali52ty3";
StringBuilder result = new StringBuilder();
foreach(char c in s)
{
if (Char.IsLetter(c))
result.Add(c);
}
Console.WriteLine(result); // quality
string text = "ABCD";
for (int i = 0; i < text.Length; i++)
{
Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i));
}
If I remember correctly, the ASCII value is the number of the lower seven bits of the Unicode number.
string value = "mahesh";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
for (int i = 0; i < value.Length; i++)
{
Console.WriteLine(value.Substring(i, 1) + " as ASCII value of: " + asciiBytes[i]);
}
This program will accept more than one character and output their ASCII value:
using System;
class ASCII
{
public static void Main(string [] args)
{
string s;
Console.WriteLine(" Enter your sentence: ");
s = Console.ReadLine();
foreach (char c in s)
{
Console.WriteLine((int)c);
}
}
}
Or in LINQ:
string value = "9quali52ty3";
var ascii_values = value.Select(x => (int)x);
var as_hex = value.Select(x => ((int)x).ToString("X02"));
If you want the charcode for each character in the string, you could do something like this:
char[] chars = "9quali52ty3".ToCharArray();
byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
MessageBox.Show("" + b);
}
Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but
I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.
string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta;
// square root
Debug.Print(s);
char c = s[0];
int i = (int)c;
string x = i.ToString("X");
c = s[1];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[2];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[3];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[4];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
The above code outputs the following to the immediate window:
a£Δ√
a 97 61
£ 163 A3
Δ 916 394
√ 8730 221A
You can remove the BOM using:
//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
targetString = sourceString.Remove(0, 1);
}
I want to get the ASCII value of characters in a string in C#.
Everyone confer answer in this structure.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
but in console we work frankness so we get a char and print the ASCII code if i wrong so please correct my answer.
static void Main(string[] args)
{
Console.WriteLine(Console.Read());
Convert.ToInt16(Console.Read());
Console.ReadKey();
}
Why not the old fashioned easy way?
public int[] ToASCII(string s)
{
char c;
int[] cByte = new int[s.Length]; / the ASCII string
for (int i = 0; i < s.Length; i++)
{
c = s[i]; // get a character from the string s
cByte[i] = Convert.ToInt16(c); // and convert it to ASCII
}
return cByte;
}
string nomFile = "9quali52ty3";
byte[] nomBytes = Encoding.ASCII.GetBytes(nomFile);
string name = "";
foreach (byte he in nomBytes)
{
name += he.ToString("X02");
}
`
Console.WriteLine(name);
// it's` better now ;)