How get the count of an array? inC# - c#

char[] charArray = startno.ToCharArray();
//using this arry
//i want to cheque this
int i=0;
count = 0;
while (chenum [i] != "0")
{
count++;
i++;
}
string s = "0";
string zero = "0";
for (i = 1; i <= count; i++)
{
s = s + zero;
}
will u help me to correct this code...
eg:(00001101) i need to add this no with 1.
for that i want to convert this value to int.if i convert to int the no will be(1101)+1 no will be (1102).after adding i want the answer (00001102).

how many zeros do you want?? You can use string.pad
int count = 1102;
int NumOfZeros = 10;
string s = count.ToString().PadLeft(NumOfZeros, '0');
there is also the number formatter.
count.ToString("D10");

String num = "000001101";
int item = int.Parse(num);
item++;
String output = item.ToString("D8");

You need to use String.Format("{0:00000000}", 1101);, which would be 00001101

If you are storing this number as an int (and you should) 1102 annd 00001102 are the same thing. Use string formatting later when you need to output the value with some zeros.
1102.ToString("D8") will give you the string "00001102"
Also, possible duplicates of this question: Pad with leading zeros

Try int.parseInt(startNo) instead of converting it to a char array.

Related

count leading number of zeros in string

i need to count leading zeros in string.
this is what i found count leading zeros in integer
static int LeadingZeros(int value)
{
// Shift right unsigned to work with both positive and negative values
var uValue = (uint) value;
int leadingZeros = 0;
while(uValue != 0)
{
uValue = uValue >> 1;
leadingZeros++;
}
return (32 - leadingZeros);
}
but couldn't found counting leading zeros in string.
string xx = "000123";
above example have 000 so i want to get result count number as 3
how i can count zeros in string?
if anyone tip for me much appreciate
The Simplest approach is using LINQ :
var text = "000123";
var count = text.TakeWhile(c => c == '0').Count();
int can't have leading 0's, however I assume you just want to count leading zeros in a string.
Without getting fancy, just use a vanilla for loop:
var input = "0000234";
var count = 0;
for(var i = 0; i < input.Length && input[i] == '0'; i++)
count++;
Full Demo Here

"Pad Left" with 0's on a char array

G'day,
I have a char array that varies in size based on the length of some data. The array will never be larger than 24 though. It may however, be less than 24. As a result of this I need to "pad left" with 0's, as in add more elements to the left of the array to make it 24. I have below some code that does this, just wondering if there is a faster way or more efficient way to do so. Thanks!
Note: I don't think this is a duplicate as I am working with char[]'s not strings.
char[] dataLen = Convert.ToString(data.Length, 2).ToCharArray();
int j = 0;
char[] tmp = new char[24];
for (int i = 0; i < 24; i++)
{
if (i < (24 - dataLen.Length))
tmp[i] = '0';
else
tmp[i] = dataLen[j++];
}
dataLen = tmp;
Why don't you simply use String.PadLeft?
char[] data = "abcdefgh".ToCharArray(); // sample data
data = new string(data).PadLeft(24, '0').ToCharArray();
That should be efficient and is also very readable.
how about :
string z24 = "000000000000000000000";
tmp = z24.Take(24 - dataLen.Length).Union(dataLen).ToArray();
I would simply use a string for all operations, and use PadLeft to do the padding.
string input = new string(data);
string result = input.PadLeft(24, '0');
Then convert it to a char[] if you really need to:
char[] chars = result.ToCharArray();
(Also, your Convert.ToString(data.Length, 2) doesn't return their string representation, new string(data) does)

Check if byte stored as string of bits is set at a given position

I have a string representing a byte or string of bits e.g "10011111". I want convert it to a bitarray and check if a bit is set at any given position e.g at position 3.
When i try convert that string to a byte it gives me a
"Value was either too large or too small for an unsigned byte." Convert.ToByte(reader[1].ToString()). Value of reader[1].ToString() = "11111111".
Please help.
You should put the base explicitly, which is 2 in your case:
Byte result = Convert.ToByte(reader[1].ToString(), 2);
try this way
string x = "111111000";
var cd = x.ToCharArray();
and then you can work accordingly
The conversion used by Convert.ToByte is using a decimal numeric system. An easy way to convert to a binary array using Linq would be:
bool[] array = "101001010101".Select(c => c == '1').ToArray();
Or to conserve memory:
string str = "1010101001011100";
var array = new BitArray(str.Length);
for (int i = 0; i < str.Length; i++)
{
array[i] = str[i] == '1';
}
Or just use the string itself:
bool isSet = str[3] == '1';

Char array wont print at indexes

I have a char array that print A-Z if i convert it to a string but when I try to get a character from an index location I get nothing? ..
char[] codes= new char[156];
for (int i = 65; i < 91; i++) codes[i] = (char)i;
Console.WriteLine(codes[2]);
Because you're starting to store the char's at index 65..
Console.WriteLine(codes[65]); // A
It has to do with the fact that you created a gigantic array but only are populating a small section of it and indexing into a portion that contains no data.
You could consider simplifying using a range..
var chars = Enumerable.Range(65, 90).Select(c => (char)c).ToArray();
Console.WriteLine(chars[2]);
Or you can modify your code to this.
char[] codes = new char[26];
for (int i = 0; i < 26; i++)
{
codes[i] = (char)i;
codes[i] += 'A';
}
Console.WriteLine(codes[2]);
You try the below code
Console.WriteLine(codes[2].ToString());
The reason is Console.WriteLine can display only the string value.

Adding numbers to a string?

I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.
To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.
You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();
Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();
AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}
static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.

Categories