I have a for loop that adds a radiobutton text at the end of a string. Here is the code:
for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
sqlQry.Text += listView1.CheckedItems[i].Text + radioButton9.Text;
}
is there a way to trim the radioButton9.Text after the loop ends?
Something like:
sqlQry.Text = sqlQry.Text.TrimEnd(',');
Right now the Result is something like: "A and B and C and"
I want it to be: "A and B and C"
I did try the code i mentioned but i cannot use:
sQlQry.Text=sqlQry.Text.TrimEnd(radioButton9.Text);
You could use string.Join
sqlQry.Text = string.Join(radioButton9.Text, listView1.CheckedItems.Cast<ListViewItem>().Select(x => x.Text));
It is a lot easier to use a different logic so that you don't put the separator there at the end in the first place.
for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
if(i != 0)
{
// Put separator in before this thing
// when this is not the first thing we add.
sqlQry.Text += radioButton9.Text;
}
sqlQry.Text += listView1.CheckedItems[i].Text;
}
You can get the Length of radioButton9.Text and do a Substring of
your sqlQry.Text
sqlQry.Text.Substring(0, sqlQry.Text.Length - radioButton9.Text.Length);
Simple solution: string.Substring(startIndex, length).
Example: sqlQry.Substring(0, sqlQry.Length - /*fixedLength*/ radioButton9.Text.Length)
This returns a string which takes off a fixed amount of characters from the end. Updated takes off the length of the radioButton9's text property's length.
Related
I'm trying to fill an array with characters from a string inputted via console. I've tried the code bellow but it doesnt seem to work. I get Index out Of Range exception in the for loop part, and i didn't understand why it occured. Is the for loop range incorrect? Any insight would be greatly appreciated
Console.WriteLine("Enter a string: ");
var name = Console.ReadLine();
var intoarray = new char[name.Length];
for (var i = 0; i <= intoarray.Length; i++)
{
intoarray[i] = name[i];
}
foreach (var n in intoarray)
Console.WriteLine(intoarray[n]);
using ToCharArray() strings can be converted into character arrays.
Console.WriteLine("Enter a string: ");
var name = Console.ReadLine();
var intoarray= name.ToCharArray();
foreach (var n in intoarray)
Console.WriteLine(n);
if you are using foreach, you should wait for the index to behave as if you were taking the value.
Console.WriteLine(n);
Since arrays start at 0 and you are counting inclusive of length, the last iteration will exceed the bounds.
Just update the loop conditional to be less than length rather than less than or equal to..
I like snn bm's answer, but to answer you question directly, you're exceeding the length of the input by one. It should be:
for (var i = 0; i <= intoarray.Length - 1; i++)
(Since strings are zero-indexed, the last character in the underlying array is always going to be in the position of arrayLength - 1.)
1: the iteration should be for (var i = 0; i < intoarray.Length; i++)
2: the code
foreach (var n in intoarray)
Console.WriteLine(intoarray[n]);
also throws an exception, for "n" is a character in the array while it's used as array index.
3: In addition there's a much easier way to convert string to char array
var intoarray = name.ToCharArray();
Here's the result
Here is your mistake. There are so many options to represent i < intoarray.Length.
for (var i = 0; i < intoarray.Length; i++) // original was i <= intoarray.Length in your code
{
intoarray[i] = name[i];
}
With linq:
// Select all chars
IEnumerable<char> intoarray =
from ch in name
select ch; // can use var instead of IEnumerable<char>
// Execute the query
foreach (char temp in intoarray)
Console.WriteLine(temp);
I'm really confused why the reverse function isn't working properly..
I currently have
List<string> decimalVector = new List<string>();
string tempString = "10"
//For Vector Representation
for (int i = 0; i < tempString.Length; i++)
{
//As long as we aren't at the last digit...
if (i != (tempString.Length-1))
{
decimalVector.Add(tempString[i].ToString() + ",");
}
else
{
decimalVector.Add(tempString[i].ToString());
}
}
Console.Write("Decimal: " + decimalOutput);
Console.Write(" Vector Representation: [");
decimalVector.Reverse();
for (int i = 0; i < decimalVector.Count; i++)
{
Console.Write(decimalVector[i]);
}
Console.Write("]");
For some reason instead of the code outputting [0,1] as it should - since that is the reverse of what is currently in the decimalVector ([1,0]) ..It prints out [01,] I am so confused. Why is it randomly moving my comma out of place? Am I doing something really stupid and not seeing it?
You're reversing the order of the elements, not the order of the characters. It's 1, followed by 0. When reversed it's 0 followed by 1,. When you print that, you get 01,.
You should not include the separating , as part of the list elements, but rather only add it when printing.
Btw there is the string.Join method, which solves your problem elegantly:
string.join(",", tempString.Select(c => c.ToString()).Reverse())
Try this:
foreach (string s in decimalVector.Reverse())
{
Console.Write(s);
}
I have a hidden input that contains some objects in it. I put string "#" between any two objects, but I want to put a string that isn't on keyboard. How can I do it?
for (int i = 0; i < MyTable.Rows.Count; i++)
{
txtRows.Value += MyTable.Rows[i]["Row"].ToString();
if (i < MyTable.Rows.Count - 1)
{
txtRows.Value += "#";
}
}
You can put any character you like in between two strings. For example to use the ASCII record separator character, use this:
if (i < MyTable.Rows.Count - 1)
{
txtRows.Value += '\x1e';
}
And then split the value back into multiple strings using the Split method:
string[] values = txtRows.Split('\x1e');
However, I'd recommend using an array or list of inputs instead:
for (int i = 0; i < MyTable.Rows.Count; i++)
{
txtRows[i].Value = MyTable.Rows[i]["Row"].ToString();
}
Of course, you'll probably have to modify how you add these hidden elements to your form, but it's a much nicer way of handling these sorts of problems.
Is there a way to store every 2 characters in a string?
e.g.
1+2-3-2-3+
So it would be "1+", "2-", "3-", "2-", "3+" as separate strings or in an array.
The simplest way would be to walk your string with a loop, and take two-character substrings from the current position:
var res = new List<string>();
for (int i = 0 ; i < str.Length ; i += 2)
res.Add(str.Substring(i, 2));
An advanced solution would do the same thing with LINQ, and avoid an explicit loop:
var res = Enumerable
.Range(0, str.Length/2)
.Select(i => str.Substring(2*i, 2))
.ToList();
The second solution is somewhat more compact, but it is harder to understand, at least to someone not closely familiar with LINQ.
This is a good problem for a regular expressio. You could try:
\d[+-]
Just find how to compile that regular expression (HINT) and call a method that returns all occurrences.
Use a for loop, and extract the characters using the string.Substring() method, ensuring you do not go over the length of the string.
e.g.
string x = "1+2-3-2-3+";
const int LENGTH_OF_SPLIT = 2;
for(int i = 0; i < x.Length(); i += LENGTH_OF_SPLIT)
{
string temp = null; // temporary storage, that will contain the characters
// if index (i) + the length of the split is less than the
// length of the string, then we will go out of bounds (i.e.
// there is more characters to extract)
if((LENGTH_OF_SPLIT + i) < x.Length())
{
temp = x.Substring(i, LENGTH_OF_SPLIT);
}
// otherwise, we'll break out of the loop
// or just extract the rest of the string, or do something else
else
{
// you can possibly just make temp equal to the rest of the characters
// i.e.
// temp = x.Substring(i);
break; // break out of the loop, since we're over the length of the string
}
// use temp
// e.g.
// Print it out, or put it in a list
// Console.WriteLine(temp);
}
I have code like this:
for (int i = 1; i < max; i++)
{
<div>#i</div>
<div>#test[i]</div>
}
I'm using MVC3 razor syntax so it might look a bit strange.
My max is always less than ten and I would like to have a value like "A", "B" .. etc appear between the first instead of the number "1", "2" .. which is the value of i. Is there an easy way I can convert i to a letter where i = 1 represent "A" and i=2 represents "B". I need to do this in C# which I can place in my MVC3 view file.
Marife
Personally I'd probably use the indexer into a string:
// Wherever you want to declare this
// As many as you'll need - the "X" is to put A=1
const string Letters = "XABCDEFGHIJKLMNOP";
...
<div>
for (int i = 1; i < max; i++)
{
<div>#i</div>
<div>#Letters[i]</div>
}
I find that simpler and more flexible than bit shifting etc, although that will certainly work too.
(char)(i + 64) will work (65 = 'A')
for (int i = 1; i < max; i++)
{
char c = (char)(i + 64); // c will be in [A..J]
...
}
You could shift i by 64 (with a 1-based index) and cast your int to a char.
If you don't need to use i anywhere else you can do this:
for (Char ch = 'A'; ch < 'K'; ch++)
{
MessageBox.Show(ch.ToString());
}
Ah, just realised the last letter isn't constant, so you would need to convert a number somwwehere.