Is there a faster way to convert a Boolean array to a decimal string other than this:
while (temp > 0)
{
str = chars[(int)(temp % 10)] + str;
temp /= 10;
}
You can use Convert.ToInt32() function.
string binaryString = "10001011";
string decimalString = Convert.ToInt32(binaryString,2).ToString();
I'm going to just assume you have named your boolean array "arrBoolean". This answer takes inspiration from mmhasannn's answer, and may not necessarily be faster. But it fixes his answer not taking your Boolean array into consideration.
string binaryString = "";
for (int ii = 0; ii < arrBoolean.Length; ii++)
{
if (arrBoolean[ii])
binaryString += "1";
else
binaryString += "0";
}
string decimalString = Convert.ToInt32(binaryString, 2).ToString();
EDIT: Below is the updated answer, with regards to Krumia's suggestions. The above answer is kept for those who just prefers it.
StringBuilder binaryBuilder = new StringBuilder();
for (int ii = 0; ii < arrBoolean.Length; ii++)
{
if (arrBoolean[ii])
binaryBuilder.Append("1");
else
binaryBuilder.Append("0");
}
string decimalString = Convert.ToInt32(binaryBuilder.ToString(), 2).ToString();
References:
http://www.dotnetperls.com/stringbuilder
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
How can I ignore characters between /* */ in string when copying to another string?
string str1 = "/*TODO:if*/";
How to ignore the caracters between /**/ so the new string will look like this:
string str2 = "/**/";
I am not allowed to use any library functions!
string str2 = Regex.Replace(str1, #"/\*.*\*/", "/**/");
Using a regular expression, you can capture all instances of /*[anything]*/ and replace it with just the text you want: /**/. However, this will be very greedy. If you have the string /*foo*/bar/*baz*/, this will eat all of it.
string str2 = Regex.Replace(str1, #"/\*.+?\*/", "/**/");
By changing it to be a lazy regex, the string /**/bar/**/ will be returned.
Given the edit above, this could also be done without Regex by doing a simple index search - though it is a greedy replacement.
string str2 = str1.Substring(0, str1.IndexOf("/*")) + "/*" + str1.Substring(str1.LastIndexOf("*/"));
This just takes everything before the first /* and then everything after the last */.
Try this code (it does not use any library function):
static string FormatString(string str) =>
RemoveAfter(str, "/*") + SubstringFrom(str, "*/");
static int IndexOf(string str, string value)
{
for (int i = 0; i < str.Length - value.Length; i++)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static int LastIndexOf(string str, string value)
{
for (int i = str.Length - value.Length; i >= 0; i--)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static string SubstringFrom(string str, string value)
{
int startIndex = LastIndexOf(str, value);
int length = str.Length - startIndex;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[startIndex + i];
}
return new string(result);
}
static string RemoveAfter(string str, string value)
{
int length = IndexOf(str, value) + value.Length;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[i];
}
return new string(result);
}
I'm not sure it makes sense that you can't use library functions, considering all functions are essentially library functions. I think the limitation here is that you can't bring in a library that doesn't already come imported in a new project. That's OK, we can do this hobbled like that. The Type string has a Split function, and failing that we can play it dirty and use indeces like it's 1995. I didn't get to test these but you should be well on your way with them. It was a fun little exercise, honestly.
Given : string str1 = "Stufftokeep/*TODO:if*/StufftokeepAgain";
string[] crazyHomework = str1.Split('/');
string result = string.Empty;
foreach(string s in crazyHomework)
{
if(s.IndexOf('*') == -1)
result += s + " "; //added a space to keep them separate
}
That gets you there using only System functions. Failing that, you can mutate the string into a lovely array of type char (which is all a string is anyway).
string result = string.Empty;
bool copy = true;
char[] array = str1.ToCharArray()
foreach(char a in array)
{
int i = array.IndexOf[a];
if(a == "/" && array.IndexOf(a) != array.Length - 1
&&
(array[a + 1] == '*' || array[a -1] == '*'))
{
copy = !copy;
}
if(copy)
result += a.ToString();
}
You'll have some space issues on that one if there isn't whitespace in the string, though.
Quick and dirty
string temp = null;
string str1 = "this shoudl remain/*TODO:if*/*/*testing again */-and so should this";
int x, y;
while ((x = str1.IndexOf("/*")) != -1)
{
if ((y = str1.IndexOf("*/")) > x)
{
temp += str1.Substring(0, x + 2) + str1.Substring(y, 2);
str1 = str1.Substring(y + 2);
continue;
}
temp += str1.Substring(y, x);
str1 = str1.Substring(x)
}
temp += str1;
Inside a For loop I do not understand following behavior of string.Substring(i,j)
having the code
String line = "TTACCTTAAC";
int k = 3; //this is variable but for simplicity is 3
String _pattern = "";
for (int i = 0; i <= line.Length - k; i++) {
_pattern = line.Substring(i, i + k );
//do something...
}
I am expecting the loop to walk over string Line (TACCTTAAC) (from 0 to 10-3 = 7)like:
TTA
ACC
CCT
CTT
TTA
TAA
AAC
However I get
TTA
ACCT
etc...
What am I missing?
Second parameter of Substring is length, not end, so you should just pass k instead of doing your math:
String line = "TTACCTTAAC";
int k = 3; //this is variable but for simplicity is 3
String _pattern = "";
for (int i = 0; i <= line.Length - k; i++) {
_pattern = line.Substring(i, k);
//do something...
}
substring function in c# is used as string.Substring(int startindex, int Length)
so you should use
_pattern = line.Substring(i, k);
My goal is to be able to convert a string into binary code that is still a string. I am able to turn the string into byte[] but not back to a string without decoding it.
You can use the Convert method for that:
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
If you can encode/decode a byte, e.g.
private static String ToBinary(Byte value) {
StringBuilder Sb = new StringBuilder(8);
Sb.Length = 8;
for (int i = 0; i < 8; ++i) {
Sb[7 - i] = (Char) ('0' + value % 2);
value /= 2;
}
return Sb.ToString();
}
private static Byte FromBinary(String value) {
int result = 0;
for (int i = 0; i < value.Length; ++i)
result = result * 2 + value[i] - '0';
return (Byte) result;
}
You can easily encode/decode a whole string:
// Encoding...
String source = "abc";
// 011000010110001001100011
String result = String.Join("", UTF8Encoding.UTF8.GetBytes(source).Select(x => ToBinary(x)));
...
// Decoding...
List<Byte> codes = new List<Byte>();
for (int i = 0; i < result.Length; i += 8)
codes.Add(FromBinary(result.Substring(i, 8)));
// abc
String sourceBack = UTF8Encoding.UTF8.GetString(codes.ToArray());
use
string str = "Welcome";
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);
string[] myString = {"a","b","c","d"}
//Reverse string algorithm here
myString = {"d","c","b","a"}
I have been asked to do so in an interview without the help of any temporary variable or .NET class, string methods, etc to reverse the elements of the same string array. I was told to use basic programming constructs like loops. Since, I am up for another interview today, I am in a hurry to know whether this is actually possible because I could not find a solution to this.
Here you go, no support variables, no .net functions :) But it makes the assumptions that all the strings in the array have length 1 ( as they do in the code you posted).
string[] myString = {"a","b","c","d", "e"};
for(int i = 0; i < myString.Length/2; i++)
{
myString[i] += myString[myString.Length -1 -i];
myString[myString.Length -1 -i] = ""+myString[i][0];
myString[i] = "" + myString[i][1];
}
Since you cannot use a temporary variable, the best I can think of is appending the strings first and then removing the appended part again:
// append last strings to first strings
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i] + myString[myString.Length - i - 1];
}
// copy first half to last half
for(int i = myString.Length / 2 + 1; i < myString.Length; i++)
{
myString[i] = myString[myString.Length - i - 1]
.SubString(0,
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
// remove useless part from first half
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i].SubString(
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
Stupid approach? Yes. But no additional variables are involved.
string[] myString = {"a","b","c","d"}
for(int = (myString.Length - 1); int >= 0; i--) {
string rev = myString[i];
Console.Write(rev);
}
Sorry I posted a wrong answer... here's the verified one:
int k = len - 1;
for(int i = 0; i<len/2; i++)
{
myString[i] = myString[i]+"."+myString[k--];
}
for(int i = len/2; i<len; i++)
{
myString[i] = myString[k].substring(0, 1);
myString[k] = myString[k--].substring(2,3);
}
However, just consider this a pseudo-code... I did not check for .NET syntax.
The right answer in your interview is "Why would you NOT use the class libraries?" But then say, "Well if I needed to write a customized method because the libraries don't support the need...". Then I would show both methods and argue when to use each method. If they had a problem with this explanation then I wouldn't want to work there anyway.
With Libraries:
string[] myString = {"a","b","c","d"};
List<string> list = myString.ToList();
list.Reverse();
myString = list.ToArray();
Without:
string[] myString = {"a","b","c","d"};
string[] newString = new string[myString.Length];
for (int i = 0, j = myString.Length - 1; i < myString.Length && j >= 0; i++, j--)
{
newString[j] = myString[i];
}
myString = newString;
This is not a complete answer, perhaps an idea..
It is possible to swap two numbers by mathematics
swap(a,b)
a = a + b
b = a - b
a = a - b
Initially I was going to suggest this can be done with character ascii values.. Then I noticed the strings.
Is it acceptable then to
swap(str1, str2)
str1 = str1+str2
str2 = str1[0]
str1 = str1[1]
I hope you get the idea
Have you tried this
string[] myString = { "a", "b", "c", "d","e","f" };
int _firstcounter = 0;
int _lastcounter = myString.Length-1;
while (_firstcounter<=_lastcounter)
{
myString[_firstcounter] += myString[_lastcounter];
myString[_lastcounter] = "" + myString[_firstcounter][0];
myString[_firstcounter] = "" + myString[_firstcounter][1];
_firstcounter++;
_lastcounter--;
}
If the maximum string length is of array is less than 10, then is might be helpful....
string[] myString = { "aaaa", "bbb", "ccccccc", "dddddd", "e", "fffffffff" };
for (int i = 0; i < myString.Length; i++)
{
myString[i] = myString[i].Length.ToString() + myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i] + myString[myString.Length-1-i];
myString[myString.Length - 1 - i] = myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i].Substring(int.Parse(myString[i][0].ToString())+2,int.Parse(myString[i][int.Parse(myString[i][0].ToString())+1].ToString()));
}
for (int i = myString.Length / 2; i < myString.Length; i++)
{
myString[i] = myString[i].Substring(1, int.Parse(myString[i][0].ToString()));
}
Try this.
public static class ExtensionMethods
{
public static IEnumerable<T> ReverseArray<T>(this T[] source)
{
for (int i = source.Length - 1; i >= 0; i--)
{
yield return source[i];
}
}
public static T[] EnumerableToArray<T>(this IEnumerable<T> source)
{
var array = new T[source.Count()];
int k = 0;
foreach (var n in source)
{
array[k++] = n;
}
return array;
}
}
Example usage
public static void Main(string[] args)
{
string[] myString = {"a", "b", "c", "d"};
myString = myString.ReverseArray().EnumerableToArray();
}
static void ReverseMyString(string[] myString)
{
int start=0, end= myString.Length-1;
string temp = "";
while (start < end)
{
temp = myString[start];
myString[start] = myString[end];
myString[end] = temp;
start++;
end--;
}
}
Yes you can do it-
string[] myString = { "a", "b", "c", "d" };
myString = (from a in myString orderby a descending select a).ToArray();
You need at least one variable to swap values.
In pseudo code:
for(i : 0..n/2) {
// swap s[i] and s[n-i]
String tmp = s[i];
s[i] = s[n-i];
s[n-i] = tmp;
}
We Can use Array.Reverse(UrArray);
Check out Array.Reverse method on MSDN.
int i = 1;
for (; i <= 10; i++)
{
string str = "test{0}" , i;
Console.WriteLine(str);
}
So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?
I think you meant to wrap that with a String.Format call.
string str = String.Format("test{0}", i);
You should try this syntax:
for (int i = 1; i <= 10; i++) {
string str = String.Format("test{0}", i);
Console.WriteLine(str);
}
The way you have defined your string doesn't look correct to me at all. I'm guessing the code you're looking for is:
int i = 1;
for(; i <= 10; i++)
{
string str = string.Format("test{0}", i);
Console.WriteLine(str);
}
But in that case there's really no reason to create a new string and call Format() for every iteration. You can create a single string and let Console.WriteLine() handle the formating.
string str = "test{0}";
for(int i = 1; i <= 10; i++)
Console.WriteLine(str, i);
My guess is you want something like this:
for(int i=1;i<=10;i++)
Console.WriteLine(String.Format("test{0}",i);
You can put any number of things in brackets, separate each input with a comma.
string Month = "Jan";
int day = 21;
string temp = String.Format("Today is:{0} - {1}/{2}",Month,day,2011);
temp gets the value "Today is:Jan - 21/2011"
In the future the desired output would be helpful.
Edit: spelling
int i;
for (; i <= 10; i++) Console.WriteLine("test{0}", i);