My goal is to create usernames that start with a "Z" and end with 000001 - 000048. I would like to store these in a list and then retrieve them to store in an Excel list. My code is buggy (FormatException), and so I am asking for assistance.
public static string GetUserName()
{
int length = 5;
int number = 0;
List<string> userNames = new List<string>();
for (int i = 1; i < 49; i++)
{
number = i;
string asString = number.ToString("Z" + length);
userNames.Add(asString);
}
return userNames.ToString();
}
In this section I would like to save the generated user names to the Excel list
var login = new List<string> { GetUserName(), GetUserName(), GetUserName() };
You can use PadLeft to format the usernames like below :
"Z" + i.ToString().PadLeft(length, '0')
The whole function could be re-written like this:
public static List<string> GetUserName()
{
int length = 6;
List<string> userNames = new List<string>();
for (int i = 1; i < 49; i++)
userNames.Add("Z" + i.ToString().PadLeft(length, '0'));
return userNames;
}
If you notice, the return type of the function is corrected and removed some unnecessary lines. And to get the list of usernames :
var login = GetUserName();
EDIT 2
You can use this method which will return 16 user names when it is called :
public static List<string> GetUserName(int startFrom)
{
int length = 6;
List<string> userNames = new List<string>();
for (int i = startFrom; i < 16 + startFrom; i++)
userNames.Add("Z" + i.ToString().PadLeft(length, '0'));
return userNames;
}
So if you need to call it 3 times, you can do it like below :
List<string> login;
for (int i = 1; i <= 48; i = i + 16)
login = GetUserName(i);
It's similar to call the function 3 times like this :
login = GetUserName(1);
login = GetUserName(17);
login = GetUserName(33);
What about changing your output of the function to what you want?
public static List<string> GetUserName()
{
int length = 5;
List<string> userNames = new List<string>();
for (int i = 1; i < 49; i++)
{
string asString = "Z"+ i.ToString().PadLeft(length, '0');
userNames.Add(asString);
}
return userNames;
}
then you can
var login = GetUserName();
You want a number with 6 digits. Your code doesn't work because the ToString() method has a standard numeric format string and a custom one, both which your format doesn't comply. You could use the 0 place holder to format a 6 digit number string and append the Z at the begining:
string asString = "Z" + number.ToString("000000");
You could also use string interpolation instead of append:
string asString = $"Z{number.ToString("000000")}";
Edit:
If you want a custom number of digits, you could initialize a string with the desired format:
string numberFormat = new string('0', length);
And use like this:
string asString = $"Z{number.ToString(numberFormat)}";
Edit 2:
You can also wrap 'Z' in the format string, as long as it is between quotes or double quotes. Also, number in your code is useless since it's equal to i, so you can simplify with:
string asString = i.ToString("'Z'000000");
You'll probably want to look into PadLeft/PadRight.
ToString is a powerful tool, but PadLeft is the thing you are looking for I believe.
"Z" + number.ToString().PadLeft(myTotalStringLength, '0').ToString() ;
I am new to C#. My problem is to take odd chars from a string and get a new string from those odds.
string name = "Filip"; // expected output ="Flp"
I don't want to take, for example,
string result = name.Substring(0, 1) + name.Substring(2, 1) + ... etc.
I need a function for this operation.
Try Linq (you actually want even characters since string is zero-based):
string name = "Filip";
string result = string.Concat(name.Where((c, i) => i % 2 == 0));
In case of good old loop implementation, I suggest building the string with a help of StringBuilder:
StringBuilder sb = new StringBuilder(name.Length / 2 + 1);
for (int i = 0; i < name.Length; i += 2)
sb.Append(name[i]);
string result = sb.ToString();
I have a string which contains binary digits. How to separate string after each 8 digit?
Suppose the string is:
string x = "111111110000000011111111000000001111111100000000";
I want to add a separator like ,(comma) after each 8 character.
output should be :
"11111111,00000000,11111111,00000000,11111111,00000000,"
Then I want to send it to a list<> last 8 char 1st then the previous 8 chars(excepting ,) and so on.
How can I do this?
Regex.Replace(myString, ".{8}", "$0,");
If you want an array of eight-character strings, then the following is probably easier:
Regex.Split(myString, "(?<=^(.{8})+)");
which will split the string only at points where a multiple of eight characters precede it.
Try this:
var s = "111111110000000011111111000000001111111100000000";
var list = Enumerable
.Range(0, s.Length/8)
.Select(i => s.Substring(i*8, 8));
var res = string.Join(",", list);
There's another Regex approach:
var str = "111111110000000011111111000000001111111100000000";
# for .NET 4
var res = String.Join(",",Regex.Matches(str, #"\d{8}").Cast<Match>());
# for .NET 3.5
var res = String.Join(",", Regex.Matches(str, #"\d{8}")
.OfType<Match>()
.Select(m => m.Value).ToArray());
...or old school:
public static List<string> splitter(string in, out string csv)
{
if (in.length % 8 != 0) throw new ArgumentException("in");
var lst = new List<string>(in/8);
for (int i=0; i < in.length / 8; i++) lst.Add(in.Substring(i*8,8));
csv = string.Join(",", lst); //This we want in input order (I believe)
lst.Reverse(); //As we want list in reverse order (I believe)
return lst;
}
Ugly but less garbage:
private string InsertStrings(string s, int insertEvery, char insert)
{
char[] ins = s.ToCharArray();
int length = s.Length + (s.Length / insertEvery);
if (ins.Length % insertEvery == 0)
{
length--;
}
var outs = new char[length];
long di = 0;
long si = 0;
while (si < s.Length - insertEvery)
{
Array.Copy(ins, si, outs, di, insertEvery);
si += insertEvery;
di += insertEvery;
outs[di] = insert;
di ++;
}
Array.Copy(ins, si, outs, di, ins.Length - si);
return new string(outs);
}
String overload:
private string InsertStrings(string s, int insertEvery, string insert)
{
char[] ins = s.ToCharArray();
char[] inserts = insert.ToCharArray();
int insertLength = inserts.Length;
int length = s.Length + (s.Length / insertEvery) * insert.Length;
if (ins.Length % insertEvery == 0)
{
length -= insert.Length;
}
var outs = new char[length];
long di = 0;
long si = 0;
while (si < s.Length - insertEvery)
{
Array.Copy(ins, si, outs, di, insertEvery);
si += insertEvery;
di += insertEvery;
Array.Copy(inserts, 0, outs, di, insertLength);
di += insertLength;
}
Array.Copy(ins, si, outs, di, ins.Length - si);
return new string(outs);
}
If I understand your last requirement correctly (it's not clear to me if you need the intermediate comma-delimited string or not), you could do this:
var enumerable = "111111110000000011111111000000001111111100000000".Batch(8).Reverse();
By utilizing morelinq.
Here my two little cents too. An implementation using StringBuilder:
public static string AddChunkSeparator (string str, int chunk_len, char separator)
{
if (str == null || str.Length < chunk_len) {
return str;
}
StringBuilder builder = new StringBuilder();
for (var index = 0; index < str.Length; index += chunk_len) {
builder.Append(str, index, chunk_len);
builder.Append(separator);
}
return builder.ToString();
}
You can call it like this:
string data = "111111110000000011111111000000001111111100000000";
string output = AddChunkSeparator(data, 8, ',');
One way using LINQ:
string data = "111111110000000011111111000000001111111100000000";
const int separateOnLength = 8;
string separated = new string(
data.Select((x,i) => i > 0 && i % separateOnLength == 0 ? new [] { ',', x } : new [] { x })
.SelectMany(x => x)
.ToArray()
);
I did it using Pattern & Matcher as following way:
fun addAnyCharacter(input: String, insertion: String, interval: Int): String {
val pattern = Pattern.compile("(.{$interval})", Pattern.DOTALL)
val matcher = pattern.matcher(input)
return matcher.replaceAll("$1$insertion")
}
Where:
input indicates Input string. Check results section.
insertion indicates Insert string between those characters. For example comma (,), start(*), hash(#).
interval indicates at which interval you want to add insertion character.
input indicates Input string. Check results section. Check results section; here I've added insertion at every 4th character.
Results:
I/P: 1234XXXXXXXX5678 O/P: 1234 XXXX XXXX 5678
I/P: 1234567812345678 O/P: 1234 5678 1234 5678
I/P: ABCDEFGHIJKLMNOP O/P: ABCD EFGH IJKL MNOP
Hope this helps.
As of .Net 6, you can simply use the IEnumerable.Chunk method (Which splits elements of a sequence into chunks) then reconcatenate the chunks using String.Join.
var text = "...";
string.Join(',', text.Chunk(size: 6).Select(x => new string(x)));
This is much faster without copying array (this version inserts space every 3 digits but you can adjust it to your needs)
public string GetString(double valueField)
{
char[] ins = valueField.ToString().ToCharArray();
int length = ins.Length + (ins.Length / 3);
if (ins.Length % 3 == 0)
{
length--;
}
char[] outs = new char[length];
int i = length - 1;
int j = ins.Length - 1;
int k = 0;
do
{
if (k == 3)
{
outs[i--] = ' ';
k = 0;
}
else
{
outs[i--] = ins[j--];
k++;
}
}
while (i >= 0);
return new string(outs);
}
For every 1 character, you could do this one-liner:
string.Join(".", "1234".ToArray()) //result: 1.2.3.4
If you intend to create your own function to acheive this without using regex or pattern matching methods, you can create a simple function like this:
String formatString(String key, String seperator, int afterEvery){
String formattedKey = "";
for(int i=0; i<key.length(); i++){
formattedKey += key.substring(i,i+1);
if((i+1)%afterEvery==0)
formattedKey += seperator;
}
if(formattedKey.endsWith("-"))
formattedKey = formattedKey.substring(0,formattedKey.length()-1);
return formattedKey;
}
Calling the mothod like this
formatString("ABCDEFGHIJKLMNOPQRST", "-", 4)
Would result in the return string as this
ABCD-EFGH-IJKL-MNOP-QRST
A little late to the party, but here's a simplified LINQ expression to break an input string x into groups of n separated by another string sep:
string sep = ",";
int n = 8;
string result = String.Join(sep, x.InSetsOf(n).Select(g => new String(g.ToArray())));
A quick rundown of what's happening here:
x is being treated as an IEnumerable<char>, which is where the InSetsOf extension method comes in.
InSetsOf(n) groups characters into an IEnumerable of IEnumerable -- each entry in the outer grouping contains an inner group of n characters.
Inside the Select method, each group of n characters is turned back into a string by using the String() constructor that takes an array of chars.
The result of Select is now an IEnumerable<string>, which is passed into String.Join to interleave the sep string, just like any other example.
I am more than late with my answer but you can use this one:
static string PutLineBreak(string str, int split)
{
for (int a = 1; a <= str.Length; a++)
{
if (a % split == 0)
str = str.Insert(a, "\n");
}
return str;
}
I am doing a program in .NET. I am doing some changes in the program. I am getting a error
String does not contain a definition for add method.
I don know how to rectify this error.
private string process(string fname)
{
//string errs = "";
string Strings = "";
string[] lines = File.ReadAllLines(fname);
StringBuilder b = new StringBuilder();
for (int i = 1; i < lines.Length; i++)
{
string[] sa = lines[i].Split(new string[] { "," }, StringSplitOptions.None);
bool ok = false;
if (sa[1].CompareTo("EQ") == 0)
ok = true;
if (!ok && sa[1].CompareTo("BE") != 0)
continue;
string name = sa[0];
int token = NSECM.Lookup(name);
if (token == 0)
{
//errs += "Symbol " + name + " not found\r\n";
continue;
}
//int open = (int)(double.Parse(sa[2]) * 100 + 0.5);
//int high = (int)(double.Parse(sa[3]) * 100 + 0.5);
//int low = (int)(double.Parse(sa[4]) * 100 + 0.5);
//int close = (int)(double.Parse(sa[5]) * 100 + 0.5);
//uint vol = uint.Parse(sa[8]);
//int date = cdate(sa[10]);
//uint time = cvt(date);
uint open = (uint)(double.Parse(sa[2]) * 100 + 0.5);
uint high = (uint)(double.Parse(sa[3]) * 100 + 0.5);
uint low = (uint)(double.Parse(sa[4]) * 100 + 0.5);
uint close = (uint)(double.Parse(sa[5]) * 100 + 0.5);
uint vol = uint.Parse(sa[8]);
int date = cdate(sa[10]);
//b.Append("D");
b.Append("S" + (1000000 + token).ToString().Substring(1));
b.Append("-" + date);
b.Append("|D");
b.Append(Encode.encode6(cvt(date)));
//b.Append(Encode.encode6(time));
b.Append(Encode.encode4(open));
b.Append(Encode.encode4(high));
b.Append(Encode.encode4(low));
b.Append(Encode.encode4(close));
b.Append(Encode.encode6(vol));
//b.Append("\n");
Strings.Add(b.ToString());
}
}
The string class does not define a method called Add therefore the line Strings.Add(b.ToString()) does not compile. Depending on what you like to do there are 2 possible solutions i can imagine of
You want to combine the current value of Strings with the value of b: Strings += b.ToString(). But keep in mind that you are always appending stuff to the same StringBuilder so in the end you add to much. But on the other hand you can just write Strings = b.ToString() after the for-loop because then you have added all your text to the StringBuilder.
You want to add the current value of b as a new string to a collection of strings. In this case Strings should be a collection. The Add method suggests that you should have a look in the List class. List<string> Strings = new List<string>();. Now you can use Strings.Add(b.ToString()). But also here keep in mind that you are always appending to the same StringBuilder without flushing it!
There is no Add() method on the string class:
Strings.Add(b.ToString());
You can concat the strings with the += operator instead:
Strings += b.ToString();
Use StringBuilder instead of string. It supports append method to concatenate strings. Moreover StringBuilder is mutable. When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed
How can I convert an int datatype into a string datatype in C#?
string myString = myInt.ToString();
string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();
Just in case you want the binary representation and you're still drunk from last night's party:
private static string ByteToString(int value)
{
StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
{
builder.Append(bit ? '1' : '0');
}
return builder.ToString();
}
Note: Something about not handling endianness very nicely...
If you don't mind sacrificing a bit of memory for speed, you can use below to generate an array with pre-calculated string values:
static void OutputIntegerStringRepresentations()
{
Console.WriteLine("private static string[] integerAsDecimal = new [] {");
for (int i = int.MinValue; i < int.MaxValue; i++)
{
Console.WriteLine("\t\"{0}\",", i);
}
Console.WriteLine("\t\"{0}\"", int.MaxValue);
Console.WriteLine("}");
}
int num = 10;
string str = Convert.ToString(num);
The ToString method of any object is supposed to return a string representation of that object.
int var1 = 2;
string var2 = var1.ToString();
Further on to #Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.
It seems pretty much a tie between:
int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
string str = intVar.ToString();
In some conditions, you do not have to use ToString()
string str = "hi " + intVar;
or:
string s = Convert.ToString(num);
using System.ComponentModel;
TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));
None of the answers mentioned that the ToString() method can be applied to integer expressions
Debug.Assert((1000*1000).ToString()=="1000000");
even to integer literals
Debug.Assert(256.ToString("X")=="100");
Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...
string s = "" + 2;
and you can do nice things like:
string s = 2 + 2 + "you"
The result will be:
"4 you"
if you're getting from a dataset
string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();