Ive got an empty string s = "";
Ive got a char b = '0';
char b is in a loop so changes after every, I want to keep adding that char b to the string s,
For example, after the first loop string s = "0"
after second round s = "01"
In Java its simple to do that for an empty string with string s += char b;
Couldnt find anything like that on C#, is there an easier way than building a string builder or making a dummy string?
What you describe works in C#:
string x = "";
x += 'Z';
Console.WriteLine(x); // Prints "Z"
Or in a loop:
string x = "";
char b = '#';
for (int i = 0; i < 10; ++i)
{
++b;
x += b;
Console.WriteLine(x); // Prints "A", then "AB", then "ABC" etc.
}
However, you should use StringBuilder for efficiency.
The same loop as above using StringBuilder:
StringBuilder x = new StringBuilder();
char b = '#';
for (int i = 0; i < 10; ++i)
{
++b;
x.Append(b);
Console.WriteLine(x); // Prints "A", then "AB", then "ABC" etc.
}
Easy, but not efficient (String s constantly re-creaing):
char b = '0';
for (int i = 0; i < n; ++i)
s += (Char)(b + i);
Better choice is to use StringBuilder:
char b = '0';
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
sb.Append((Char)(b + i));
s = sb.ToString();
Related
I am trying to see weather the string is in alphabetical order or no and this error pops up
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at Rextester.Program.Main(String[] args)**
public static void Main(string[] args)
{
string str = "bat\ncat\ndog\n";
int c = 0;
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
c++;
}
}
String[] strArray = new String[c + 1]; //declare with size
int g = 0;
String h = "";
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
strArray[g] = h;
h = "";
g = g + 1;
}
else
{
h = h + str.Substring(i,i + 1);
}
}
String p = "True";
for (int i = 0; i < g; i++)
{
if (i < (g - 1))
{
String f = strArray[i];
String g2 = strArray[i + 1];
char d = f[0];
char s = g2[0];
int d1 = (int)d;
int s1 = (int)s;
if (d1 > s1)
{
p = "False";
}
}
}
Console.WriteLine(p);
}
}
Not sure about what you are doing in your second loop and why is it so complex. We can do the same like this. Hope this helps.
using System;
public class Program
{
public static void Main()
{
string str = "abcd";
str = str.Replace('\n',' ');
String p = "True";
for (int i = 1; i < str.Length; i++) {
// if element at index 'i' is less
// than the element at index 'i-1'
// then the string is not sorted
if (str[i] < str[i - 1]) {
p = "false";
}
}
Console.WriteLine(p);
}
}
Pay attention to the definition of substring
The substring starts at a specified character position and has a
specified length
Considering your first use of substring, here
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, i + 1).Equals("\n"))
{
c++;
}
}
What happens when we get to i=6 here? Substring tries to give you a new string that starts at position i = 6, and is length = 7 characters long. So it tries to give you 7 characters starting from str[6] to str[12]. Well, there is no str[12], so you get an exception.
Its clear that your intent is NOT to get a string that starts at position 6 and is 7 characters long. You want ONE character, so your loop should be this
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1).Equals("\n"))
{
c++;
}
}
But theres a much simpler way to get your words in alphabetical order using LINQ
string str = "bat\ncat\ndog\n";
//Removes the trailing \n so you don't have one entry that is only whitespace
str = str.Trim();
string[] strSplit = str.Split('\n').OrderBy(x => x[0]).ToArray();
Now all substrings are sorted alphabetically and you can do whatever you want with them
How do I get all alpha-number combo's in a given alpha-number combo range using c#?
For getting all numbers in a range I'll do something like below
int x = 10;
int y = 15;
int z=y-x+1;
var range =Enumerable.Range(x,z);
foreach (var element in range)
{
Console.WriteLine(element.ToString()+"-->"+x.ToString()+"-"+y.ToString());
}
Console.ReadLine();
But when the value of x is like 1x and y is like 2b how do I get the range of strings like below?
1x
1y
1z
2a
2b
First, parse the string to get the numerical value and the character. Then, loop for each number from the start to the end. Inside, loop for each character in the alphabet from the start to the current end.
Here you go:
string x = "1x";
string y = "2b";
char startCharacter = x.Substring(x.Length-1)[0];
char endCharacter = y.Substring(y.Length-1)[0];
int startNumber = int.Parse(x.Substring(0, x.Length - 1));
int endNumber = int.Parse(y.Substring(0, y.Length - 1));
var range = new List<string>();
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i = startNumber; i <= endNumber; ++i) {
int currentCharEnd = (i == endNumber) ? alphabet.IndexOf(endCharacter) : alphabet.Length - 1;
for(int j = alphabet.IndexOf(startCharacter); j <= currentCharEnd; ++j) {
range.Add(i.ToString() + alphabet[j]);
}
startCharacter = 'a';
}
// range is now { "1x", "1y", "1z", "2a", "2b" }
You can start by doing this, and extend it to achieve your task fully.
string[] abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
string x = "1g";
string y = "2b";
string strx = Regex.Match(x, #"\d+").Value;
string stra = Regex.Match(x, #"[a-z]+").Value;
int intx = Int32.Parse(strx);
string stry = Regex.Match(y, #"\d+").Value;
string strb = Regex.Match(x, #"[a-z]+").Value;
int inty = Int32.Parse(stry);
Console.WriteLine(strx);
Console.WriteLine(stra);
Console.WriteLine("----");
int len = inty - intx + 1;
List<string> xycombinations = new List<string>();
string[] ycombinations = new string[] { };
if (len >= 0)
{
int starting = 0;
while (abc[starting] != stra)
{
starting = starting + 1;
}
while (starting < abc.Length)
{
xycombinations.Add(intx.ToString() + abc[starting]);
starting = starting + 1;
}
for (int i = 0; i < xycombinations.Count; i++)
{
Console.WriteLine(xycombinations[i]);
}
}
Console.ReadLine();
It only makes the combination of string x till the end, for instance string x is "1g", so this code makes combinations 1g, 1h, 1i, ij. Similarly you can make combinations of string y by extending. Hope it helps you.
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);
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.
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.