C# string manipulation, why this doesn't work? - c#

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);

Related

Outputting a _ for each letter of a string in an array (hangman)

public void Dashes()
{
for (int i = 0; i < SelectedWord.Length; i++)
console.WriteLine("_");
}
this is the only thing i can think of and whenever I go to run it puts it on all separate lines when I want it on 1 line
public void Dashes()
{
for (int i = 0; i < SelectedWord.Length; i++)
console.Write("_");
}
Thanks to #Grant Winney
Try this
string output = "";
for (int i = 0; i < SelectedWord.Length; i++)
{
output += "_";
}
console.WriteLine(output);
The console,writeline prints starts a new line everytime its called in your loop.
public void Dashes()
{
string dashes ="";
for (int i = 0; i < SelectedWord.Length; i++)
dashes +="_";
console.WriteLine(dashes);
}
You can also ditch the loop entirely if running .NET 4 or above and use the following single line (as per this answer):
console.WriteLine(String.Concat(Enumerable.Repeat("_", SelectedWord.Length)));

String.Substring behavior when moving a string frame k char places

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);

How do I Concat a loop of a char random array?

I have a char array like this:
char[] true_false = new char[2]{'V','F'};
A variable random:
Random rand = new Random();
I have a string called generate_code, with the initial value is true_false[rand.Next(0, 2)].ToString();
string generate_code = true_false[rand.Next(0, 2)].ToString();
And the user will set the int lenght_of;
int lenght_of = int.Parse(Console.ReadLine());
So, what I am trying to do is: the user will define the lenght_of that will be the lenght of the generate_code like this:
for(int i =0; i < lenght_of;i++){
generate_code = generate_code + (char)true_false[rand.Next(0, 2)];
}
But the problem is that I need a fixed variable like :
generate_code = (char)true_false[rand.Next(0, 2)] + (char)true_false[rand.Next(0, 2)];
if lenght_of =2; and I have a loop that will change the generate_code value ten times.How can I do that? **I hope that u guys understand it is hard to explain.
Example:
lenght_of = 2;
//Example "FF";
generate_code = true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)];
for(int i =0; i < 10;i++) {
Console.WriteLine(generate_code);
} //Output expected: "FF" "VV" "FV" "VF" "FF"
Your problem is that you're adding two char's together. char is a numeric type.. therefore you're getting numbers as the result. Also, your generate_code assignment must be inside your loop:
for(int i =0; i < 10;i++) {
generate_code = string.Format("{0}", generateCodeWithLength(rand, true_false, lenght_of));
Console.WriteLine(generate_code);
}
Wrap the code generation in a method that accepts the length:
public string generateCodeWithLength(Random rand, char[] true_false, int length) {
var result = new StringBuilder(length);
for (var i = 0; i < length; i++) {
result.Append(true_false[rand.Next(0, 2)]);
}
return result.ToString();
}
Or better yet.. a StringBuilder. Clicky clicky live example.
Alternatively you can also do something like:
for(int i =0; i < 10;i++) {
Console.WriteLine(string.Format("{0}{1}", true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)]));
}
You need to refresh generate_code in each iteration of the loop:
for(int i =0; i < 10;i++) {
int loopCounter = 0;
while (loopCounter < length_of)
{
generate_code += true_false[rand.Next(0, 2)]; //Add one more char to generate_code
loopCounter += 1;
}
Console.WriteLine(generate_code);
} //Output expected if length_of = 3: "FFV" "VFV" "FVF" "FFF" "VVV"
That way, each output will be random.

Faster binary to decimal string conversion

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

Reverse elements of a string array

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.

Categories