i have an array of integer called digits
public String toDecimalString() {
StringBuilder b = new StringBuilder(9 * digits.length);
Formatter f = new Formatter(b);
f.format("%d", digits[0]);
for(int i = 1 ; i < digits.length; i++) {
f.format("%09d", digits[i]);
}
return b.toString();
}
I tried
String.Format("%09d", digits[i]);
but I think I'm doing something wrong
I'm not really familiar with java formatters, but I think this is what you want
var str = string.Format("{0:D9}", digits[i]);
Or even better
var str = digits[i].ToString("D9");
To join all these strings I suggest this:
var str = string.Join(string.Empty, digits.Select(d => d.ToString("D9")));
Further Reading
Standard Numeric Format Strings
Custom Numeric Format Strings
I think you want something like
StringBuilder sb = new StringBuilder();
sb.append(String.Format("DL", digits[i]));
for (int i = 1; i < digits.Length; i++) {
sb.append(String.Format("D9", digits[i]));
}
Copy from java code and paste it directly into c# code, then change (which are in your toDecimalString() method):
f.format to f.Format
digits.length to digits.Length
b.toString() to b.ToString()
and then paste this class to your code:
public partial class Formatter: IFormatProvider, ICustomFormatter {
public String Format(String format, object arg, IFormatProvider formatProvider=null) {
if(!format.StartsWith("%")||!format.EndsWith("d"))
throw new NotImplementedException();
m_Builder.Append(String.Format("{0:D"+format.Substring(1, format.Length-2)+"}", arg));
return m_Builder.ToString();
}
object IFormatProvider.GetFormat(Type formatType) {
return typeof(ICustomFormatter)!=formatType?null:this;
}
public Formatter(StringBuilder b) {
this.m_Builder=b;
}
StringBuilder m_Builder;
}
Note that the class only implemented the minimum requirement as your question stated, you would need to add the code if your further extend the requirement.
public string toDecimalString()
{
StringBuilder b = new StringBuilder(9 * digits.Length);
var str = digits[0].ToString("D");
b.Append(str);
for (int i = 1; i < digits.Length; i++)
{
var str2 = digits[i].ToString("D9");
b.Append(str2);
}
return b.ToString();
}
Thanks for all the answers, I finally reached a solution as above
Related
Is there a way to trim a string to the first numeric digit from left AND right using standard .NET tools? Or I need to write my own function (not difficult, but I'd rather use standard methods). I need the following outputs for the provided inputs:
Input Output
-----------------------
abc123def 123
;'-2s;35(r 2s;35
abc12de3f4g 12de3f4
You'll need to use regular expressions
string TrimToDigits(string text)
{
var pattern = #"\d.*\d";
var regex = new Regex(pattern);
Match m = regex.Match(text); // m is the first match
if (m.Success)
{
return m.Value;
}
return String.Empty;
}
If you want to call this like you normally would the String.Trim() method, you can create it as an extension method.
static class StringExtensions
{
static string TrimToDigits(this string text)
{
// ...
}
}
And then you can call it like this:
var trimmedString = otherString.TrimToDigits();
No, there is no built in way. You will have to write your own method to do this.
No, I don't think there is. Method though:
for (int i = 0; i < str.Length; i++)
{
if (char.IsDigit(str[i]))
{
break;
}
str = string.Substring(1);
}
for (int i = str.Length - 1; i > 0; i--)
{
if (char.IsDigit(str[i]))
{
break;
}
str = string.Substring(0, str.Length - 1);
}
I think this'll work.
I have a StringBuilder that accumulates code. In some cases, it has 2 empty lines between code blocks, and I'd like to make that 1 empty line.
How can I check if the current code already has an empty line at the end? (I prefer not to use its ToString() method because of performance issues.)
You can access any character of your StringBuilder with its index, like you would with a String.
var sb = new StringBuilder();
sb.Append("Hello world!\n");
Console.WriteLine(sb[sb.Length - 1] == '\n'); // True
You can normalize the newlines, using a regex:
var test = #"hello
moop
hello";
var regex = new Regex(#"(?:\r\n|[\r\n])+");
var newLinesNormalized = regex.Replace(test, Environment.NewLine);
output:
hello
moop
hello
Single line check. Uses a string type, not StringBuilder, but you should get the basic idea.
if (theString.Substring(theString.Length - Environment.NewLine.Length, Environment.NewLine.Length).Contains(Environment.NewLine))
{
//theString does end with a NewLine
}
else
{
//theString does NOT end with a NewLine
}
Here is the complete example.
class string_builder
{
string previousvalue = null;
StringBuilder sB;
public string_builder()
{
sB = new StringBuilder();
}
public void AppendToStringBuilder(string new_val)
{
if (previousvalue.EndsWith("\n") && !String.IsNullOrEmpty(previousvalue) )
{
sB.Append(new_val);
}
else
{
sB.AppendLine(new_val);
}
previousvalue = new_val;
}
}
class Program
{
public static void Main(string[] args)
{
string_builder sb = new string_builder();
sb.AppendToStringBuilder("this is line1\n");
sb.AppendToStringBuilder("this is line2");
sb.AppendToStringBuilder("\nthis is line3\n");
}
}
I've got 'funny' answer:
var sb = new StringBuilder();
sb.AppendLine("test");
sb.AppendLine("test2");
Console.WriteLine(sb.ToString().TrimEnd('\n').Length != sb.ToString().Length); //true
Since I don't care about 2 empty lines in the middle of the code, the simplest way is to use
myCode.Replace(string.Format("{0}{0}", Environment.NewLine),Environment.NewLine);
This option doesn't require any changes to classes that use the code accumulator.
In-case anyone ends up here like I did here is a general method to check the end of a StringBuilder for an arbitrary string with having to use ToString on it.
public static bool EndsWith(this StringBuilder haystack, string needle)
{
var needleLength = needle.Length - 1;
var haystackLength = haystack.Length - 1;
if (haystackLength < needleLength)
{
return false;
}
for (int i = 0; i < needleLength; i++)
{
if (haystack[haystackLength - i] != needle[needleLength - i])
{
return false;
}
}
return true;
}
at a recent interview I attended, the programming question that was asked was this. Write a function that will take as input two strings. The output should be the result of concatenation.
Conditions: Should not use StringBuffer.Append or StringBuilder.Append or string objects for concatenation;that is, they want me to implement the pseudo code implementation of How StringBuilder or StringBuffer's Append function works.
This is what I did:
static char[] AppendStrings(string input, string append)
{
char[] inputCharArray = input.ToCharArray();
char[] appendCharArray = append.ToCharArray();
char[] outputCharArray = new char[inputCharArray.Length + appendCharArray.Length];
for (int i = 0; i < inputCharArray.Length; i++)
{
outputCharArray[i] = inputCharArray[i];
}
for (int i = 0; i < appendCharArray.Length; i++)
{
outputCharArray[input.Length + i] = appendCharArray[i];
}
return outputCharArray;
}
While this is a working solution, is there a better way of doing things?
is LINQ legal? strings are just can be treated as an enumeration of chars, so they can be used with LINQ (even though there is some cost involved, see comments):
string a = "foo";
string b = "bar";
string c = new string(a.AsEnumerable().Concat(b).ToArray());
or with your method signature:
static char[] AppendStrings(string input, string append)
{
return input.AsEnumerable().Concat(append).ToArray();
}
You can call CopyTo:
char[] output = new char[a.Length + b.Length];
a.CopyTo(0, output, 0, a.Length);
b.CopyTo(0, output, a.Length, b.Length);
return new String(output);
If they don't like that, call .ToCharArray().CopyTo(...).
You can also cheat:
return String.Join("", new [] { a, b });
return String.Format("{0}{1}", a, b);
var writer = new StringWriter();
writer.Write(a);
writer.Write(b);
return writer.ToString();
I would've done something like the following (argument checking omitted for brevity)
public static string Append(string left, string right) {
var array = new char[left.Length + right.Length];
for (var i = 0; i < left.Length; i++) {
array[i] = left[i];
}
for (var i = 0; i < right.Length; i++) {
array[i + left.Length] = right[i];
}
return new string(array);
}
In Java you can just use concat which does not use StringBuilder or StringBuffer.
String a = "foo";
String b = "bar";
String ab = a.concat(b);
The source for String.concat(String) from Oracle's JDK.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
java default support "+" for append string
String temp="some text";
for(int i=0;i<10;i++)
{
temp=temp+i;
}
Or
temp=temp+" some other text"
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();
Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow?
Regex?
Definitely regex:
string CleanPhone(string phone)
{
Regex digitsOnly = new Regex(#"[^\d]");
return digitsOnly.Replace(phone, "");
}
or within a class to avoid re-creating the regex all the time:
private static Regex digitsOnly = new Regex(#"[^\d]");
public static string CleanPhone(string phone)
{
return digitsOnly.Replace(phone, "");
}
Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).
You can do it easily with regex:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
You don't need to use Regex.
phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())
Here's the extension method way of doing it.
public static class Extensions
{
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(#"[^\d]");
return digitsOnly.Replace(input, "");
}
}
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
How about an extension method that doesn't use regex.
If you do stick to one of the Regex options at least use RegexOptions.Compiled in the static variable.
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
This builds on Usman Zafar's answer converted to a method group.
for the best performance and lower memory consumption , try this:
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
private static Regex digitsOnly = new Regex(#"[^\d]");
public static void Main()
{
Console.WriteLine("Init...");
string phone = "001-12-34-56-78-90";
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
DigitsOnly(phone);
}
sw.Stop();
Console.WriteLine("Time: " + sw.ElapsedMilliseconds);
var sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < 1000000; i++)
{
DigitsOnlyRegex(phone);
}
sw2.Stop();
Console.WriteLine("Time: " + sw2.ElapsedMilliseconds);
Console.ReadLine();
}
public static string DigitsOnly(string phone, string replace = null)
{
if (replace == null) replace = "";
if (phone == null) return null;
var result = new StringBuilder(phone.Length);
foreach (char c in phone)
if (c >= '0' && c <= '9')
result.Append(c);
else
{
result.Append(replace);
}
return result.ToString();
}
public static string DigitsOnlyRegex(string phone)
{
return digitsOnly.Replace(phone, "");
}
}
The result in my computer is:
Init...
Time: 307
Time: 2178
I'm sure there's a more efficient way to do it, but I would probably do this:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
try this
public static string cleanPhone(string inVal)
{
char[] newPhon = new char[inVal.Length];
int i = 0;
foreach (char c in inVal)
if (c.CompareTo('0') > 0 && c.CompareTo('9') < 0)
newPhon[i++] = c;
return newPhon.ToString();
}