There is an error with that string.compiler thingy and i dont know what to do. i really need some help please
char[] valWord = new char[100];
Console.WriteLine(textBox1.Text);
valWord = textBox1.Text;
int beg = 0;
int val = 0;
int value = 0;
for (int i = 0; i < 100; i++)
{
if (valWord[i] == ' ' || valWord[i] == '\0')
{
char[] temp = new char[100];
for (int j = 0; j < i - beg; j++)
{
temp[j] = valWord[beg + j];
}
temp[i - beg] = '\0';
//there is an error in this if statement: String.Compare
if (String.Compare(temp, "thousand") == 0)
{
value += (val*1000);
val = 0;
}
else if (String.Compare(temp, "hundred") == 0)
{
value += (val*100);
val = 0;
}
else if (String.Compare(temp, "one") == 0)
{
val = 1;
}
else if (String.Compare(temp, "two") == 0)
{
val = 2;
}
if (valWord[i] == '\0')
{
value += val;
break;
}
}
Console.WriteLine(textBox2.Text);
}
else
{
_list.Add(name, new GenericList());
}
You can't compare a string to a char array. They are different types.
Use if (string.Equals(new string(temp),"thousand")) instead.
As per MSDN, there is no such function overload defined for String.Compare
Related
I need make symmetric letter “W” in string Array
get_w() Is method that should return string array that contains letter "W"
get_w(5) # should return:
public string[] GetW(int h)
{
if (h < 2) return new string[h];
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
str[i] = c[i].ToString();
}
return str;
}
if I compile it in a VS i get no errors.Here is an example of the result
This task is taken from the Codewars
but if I try to test on Codewars with the code I described above, I get this error
Edited:I changed returning array with "h" length to empty array and had got this
i found the task solution by replacing charters that equal '\0' with character ' '
here is working code
public string[] GetW(int h)
{
if (h < 2) return new string[]{};
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
c[i].Replace('\0', ' ');
str[i] = c[i].ToString();
}
return str;
}
And here is result of test
I have to find subtext in text without using builtin function of string.
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int i, j, found;
int strLen, wordLen;
strLen = text.Length;
wordLen = subtext.Length;
for (i = 0; i < strLen - wordLen; i++)
{
found = 1;
for (j = 0; j < wordLen; j++)
{
if (text[i + j] != subtext[j])
{
found = 0;
break;
}
}
if (found == 1)
{
Console.WriteLine(" found at index:", subtext, i);
Console.ReadLine();
}
}
}
I am not sure how long you would like to search, your current code seems to find all indexes (or at least that seems to be the intent)
Some things you could change however is instead of always starting the loop, you could validate the if the char at position i matches the first char of the subtext, and if not continue.
When you want to write the data to the console, don't forget to add the spaceholders for your arguments, like:
Console.WriteLine("found {0} at index: {1}", subtext, i);
For the rest, I guess your current implementation is okay, but you could add some validations, like ensuring that both texts are available, and if subtext is longer than the text, simply return -1 directly.
For a simple find of first index, I wrote this one up, it still looks pretty similar to yours
private static int FindIn( string text, string sub ) {
if (string.IsNullOrWhiteSpace( text ) || string.IsNullOrWhiteSpace( sub ) ) {
return string.IsNullOrWhiteSpace( sub ) ? 0 : -1;
}
if (text.Length < sub.Length) {
return -1;
}
for (int i = 0; i < text.Length - sub.Length; i++) {
if (text[i] != sub[0]) {
continue;
}
var matched = true;
for (int j = 1; j < sub.Length && i + j < text.Length; j++) {
if (text[i+j] != sub[j]) {
matched = false;
break;
}
}
if (matched) {
return i;
}
}
return -1;
}
Which you can play around with here
There are a lot of pattern-matching algorithms in this book, i will leave here c# implementation of Knuth-Morris-Pratt algorithm.
static int[] GetPrefix(string s)
{
int[] result = new int[s.Length];
result[0] = 0;
int index = 0;
for (int i = 1; i < s.Length; i++)
{
while (index >= 0 && s[index] != s[i]) { index--; }
index++;
result[i] = index;
}
return result;
}
static int FindSubstring(string pattern, string text)
{
int res = -1;
int[] pf = GetPrefix(pattern);
int index = 0;
for (int i = 0; i < text.Length; i++)
{
while (index > 0 && pattern[index] != text[i]) { index = pf[index - 1]; }
if (pattern[index] == text[i]) index++;
if (index == pattern.Length)
{
return res = i - index + 1;
}
}
return res;
}
If you are looking for all occurance of the subtect in the text you can use the following code:
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int index = 0;
int startPosition = 0;
bool found = false;
while (index < text.Length - 1)
{
if (subtext[0] == text[index])
{
startPosition = index;
index++;
for (int j = 1; j <= subtext.Length - 1; j++)
{
if (subtext[j] != text[index])
{
found = false;
break;
}
else
{
found = true;
}
index++;
}
}
if (found)
{
Console.WriteLine("{0} found at index: {1}", subtext, startPosition);
found = false;
}
index++;
}
Console.ReadLine();
}
If you are looking only for the first occurance add break in the "if (found)" condition
I want to develop method that will return the length of largest substring composed of identical characters form string that is passed as argument, but without using any of .NET libraries.
For example if we pass aaacccccdefffgg as parameter the biggest substring is ccccc and method should return 5.
Here is my working solution :
public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;
for (int i = 0; i < myArray.Length-1; i++)
{
if (myArray.Length == 0)
{
return 0;
}
else
{
int j = i + 1;
int currentMax = 1; // string has some value, so we start with 1
while (myArray[i] == myArray[j])
{
currentMax++;
if (max < currentMax)
{
max = currentMax;
}
j++;
}
}
}
return max;
}
The code above will return expected result, but there will be some unnecessary iteration in for loop that I want to avoid. In first iteration when i=0it will compare it until j=2 and then will get out of while loop and start second iteration in for loop comparing the one at [1] index with [2], which we already did in previous iteration.So basically, when first iteration is completed, next one should start from the last value of j. How can I achieve that ?
Thank You in advance.
Since you want "Largest substring..." let's take String as argument and return String
public static String GetMaxSubstring(String value) {
if (String.IsNullOrEmpty(value))
return "";
int bestCount = 0;
char bestChar = '\0';
int currentCount = 0;
char current = '\0';
for (int i = 0; i < value.Length; ++i) {
if ((i == 0) || (value[i] != current))
currentCount = 0;
currentCount += 1;
current = value[i];
if (currentCount > bestCount) {
bestCount = currentCount;
bestChar = current;
}
}
return new String(bestChar, bestCount);
}
....
// "ccccc"
String result = GetMaxSubstring("aaacccccdefffgg");
// 5
int length = result.Length;
Another approach:
public static int MaxSubstringLength(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
int max = 0, cur = 1;
for (int i = 1; i < s.Length; ++i, ++cur)
{
if (s[i] != s[i-1])
{
max = cur > max ? cur : max;
cur = 0;
}
}
return cur > max ? cur : max;
}
[EDIT] Simplified the code.
[EDIT2] Simplified the code further.
you also can do it with one loop:
public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;
char currentchar = myArray[0];
int count = 1;
for each(char c in myArray)
{
if(currentchar != c)
{
count = 1;
currentchar = c;
}
if(count > max)
{
max = count;
}
count++;
}
return max;
}
I changed the code... now this code does not use math.max and I think I eleminated the mistake... I've no IDE at the moment to test it
public static int GetMaxSubstringLenght(char[] myArray)
{
if (myArray.Length == 0)
return 0;
if (myArray.Length == 1)
return 1;
int max = 1;
int localMax = 1;
for (int i = 0; i < myArray.Length - max; i++ )
{
if (myArray[i] == myArray[i + 1])
{
localMax++;
}
else
{
max = Math.Max(max, localMax);
localMax = 1;
}
}
return Math.Max(max, localMax);
}
static int LongestCharSequence(string s)
{
if (string.IsNullOrEmpty(s)) return 0;
var prevChar = '\0';
int cmax = 0;
int max = 1;
foreach (char c in s)
{
if (c != prevChar)
{
cmax = 1;
prevChar = c;
}
else
{
if (++cmax > max) max = cmax;
}
}
return max;
}
recursion!
static int LongestCharSequence(string s)
{
int i = (s?.Length ?? 0) == 0 ? 0 : 1;
for (; i < s?.Length; i++)
if (s[i] != s[i - 1]) return Math.Max(i, LongestCharSequence(s.Substring(i)));
return i;
}
Another solution using my favorite nested loop technique:
public static int MaxSubstringLength(string s)
{
int maxLength = 0;
for (int length = s != null ? s.Length : 0, pos = 0; pos < length;)
{
int start = pos;
while (++pos < length && s[pos] == s[start]) { }
maxLength = Math.Max(maxLength, pos - start);
}
return maxLength;
}
I've written a recursive method in C# that should indent strings. For example, this string:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
should be converted to:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
My method is (updated):
private static string IndentText(string t,bool first = true)
{
if (first == false)
{
t = t.PadLeft(2);
}
int startIndex = t.IndexOf('{') + 1;
int stopIndex = t.LastIndexOf('}') - 1;
int blockLength = stopIndex - startIndex + 1;
if (blockLength <= 1 )
{
return "";
}
string start = t.Substring(0, startIndex);
string end = t.Substring(stopIndex + 1);
string indentBlock = t.Substring(startIndex, blockLength);
if (!CheckNestedBlocks(indentBlock))
{
return indentBlock;
}
return start + IndentText(indentBlock,false) + end;
}
private static bool CheckNestedBlocks(string t)
{
for (int i = 0; i < t.Length; i++)
{
if (t[i] == '{') // { and } always come in pairs, so I can check of only one of then
{
return true;
}
}
return false;
}
But I'm getting a StackOverflow exception in mscorlib.dll
What is my mistake? Thanks in advance.
By the way, because I think I'm complicating this problem, is there a better (and working) way to indent strings like this?
You should not include the braces in the "block" that is passed in the recursive call:
if (t[i] == '{')
{
startIndex = i + 1; // Start one character beyond {
break;
}
// ...
if (t[i] == '}')
{
stopIndex = i - 1; // Stop one character prior to }
break;
}
I have written the following code in an effort to try and compute the values down there below, but all my arrays do not work; especially the ones in the for loops. Can someone help teach me how to declare an array inside a loop? They keep showing errors like "Did you miss declaring a new object?"
Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public class seasonal
{
public float mTotal;
public float movingAverage;
public int y;
public char quarter;
public char ssq;
public int rank;
public float forecast;
public float centralMovingAverage;
public float cmTotal;
public float sSeasonal;
}
public static int i;
public static int j;
public static int k = 0;
public static int n;
static void Main(string[] args)
{
int x; int r; int m; int c; int u = 0;
seasonal temp = new seasonal();
int n1; int n2; int n3; int n4; int sumr1 = 0; int sumr2 = 0; int sumr3 = 0; int sumr4 = 0;
float h; float ss; float sum; float sums1 = 0; float sums2 = 0; float sums3 = 0; float sums4 = 0; float tsums;
Console.WriteLine("Enter the no. of observations");
string nObservations = Console.ReadLine();
n = Convert.ToInt32(nObservations);
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
for (i = 0; i < n; i++)
{
Console.Write("{0:D}:", (i+1) );
string value = Console.ReadLine();
int observation = Convert.ToInt32(value);
seasonal thisSeasonal = new seasonal();
thisSeasonal.y = observation;
seasonal[i] = thisSeasonal;
if (i>=0 && i<3)
{
seasonal[i].quarter = '1';
}
if (i>=3 && i<6)
{
seasonal[i].quarter = '2';
}
if (i>=6 && i<9)
{
seasonal[i].quarter = '3';
}
if (i>=9 && i<12)
{
seasonal[i].quarter = '4';
}
if (i>12)
{
r = i % 12;
if (r>=0 && r<3)
{
seasonal[i].quarter = '1';
}
if (r>=3 && r<6)
{
seasonal[i].quarter = '2';
}
if (r>=6 && r<9)
{
seasonal[i].quarter = '3';
}
if (r>=9 && r<12)
{
seasonal[i].quarter = '4';
}
}
for (i = k; i < n-3; i++)
{
sum = 0;
for (j = u+k; j < 4+k; j++)
{
sum += seasonal[j].y;
seasonal[i].mTotal = sum;
seasonal[i].movingAverage = seasonal[i].mTotal / 4;
Console.Write("{0:f}", seasonal[i].movingAverage);
k++;
}
}
for ( i = 0; i < (n-4); i++)
{
ss = 0;
for (j = 0; j < (2+i); j++)
{
ss += seasonal[j].movingAverage;
}
seasonal[i].cmTotal = ss;
seasonal[i].centralMovingAverage = seasonal[i].cmTotal / 2;
seasonal[i].sSeasonal = (seasonal[i+2].y)/(seasonal[i].centralMovingAverage);
if (i == 0 || i % 4 == 0)
{
seasonal[i].ssq = '3';
}
if (i == 1 || i % 4 == 1)
{
seasonal[i].ssq = '4';
}
if (i == 2 || i % 4 == 2)
{
seasonal[i].ssq = '1';
}
if (i == 3 || i % 4 == 3)
{
seasonal[i].ssq = '2';
}
Console.Write("\n{0:f}", seasonal[i].centralMovingAverage);
Console.Write("\n {0:f}", seasonal[i].sSeasonal);
}
}
for (m= 0; m < n; m++)
{
s[m] = seasonal[m];
}
for ( i = 0; i < (n-5); i++)
{
for ( j = 0; j < (n-4); j++)
{
if (s[i].sSeasonal > s[j].sSeasonal)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for ( k = 0; k < (n-4); k++)
{
s[k].rank = k + 1;
Console.Write("\n\t {0:D}", s[k].rank);
}
for ( i = 0; i < (n-4); i++)
{
if (s[i].ssq == '1')
{
sumr1 += s[i].rank;
sums1 += s[i].sSeasonal;
//n1 ++;
}
if (s[i].ssq == '2')
{
sumr2 += s[i].rank;
sums2 += s[i].sSeasonal;
//n2++;
}
if (s[i].ssq == '3')
{
sumr3 += s[i].rank;
sums3 += s[i].sSeasonal;
//n3++;
}
if (s[i].ssq == '4')
{
sumr4 += s[i].rank;
sums4 += s[i].sSeasonal;
//n4++;
}
}
tsums = ((sums1/4)+(sums2/4)+(sums3/4)+(sums4/4));
Console.Write("\n\n\n{0:f}",tsums);
Console.Write("\n\n\n\n\n{0:D}",sumr1);
Console.Write("\n\n\n\n{0:D}",sumr2);
Console.Write("\n\n\n\n{0:D}",sumr3);
Console.Write("\n\n\n\n\n{0:D}",sumr4);
Console.Write("\n{0:f}",sums1/4);
Console.Write("\n\n{0:f}",sums2/4);
Console.Write("\n\n{0:f}",sums3/4);
Console.Write("\n\n{0:f}",sums4/4);
Console.Write("\n{0:f}",((sums1/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums2/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums3/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums4/4)/tsums)*4);
}
}
}
You need to initialise the objects in your arrays:
Seasonal[] seasonal = new Seasonal[n];
for (int l = 0; l < seasonal.Length; l++)
{
seasonal[l] = new Seasonal();
}
Seasonal[] s = new Seasonal[n];
for (int l = 0; l < s.Length; l++)
{
s[l] = new Seasonal();
}
This only solves the initialisation problem, though. You may want to look at naming conventions for readability, and then the index off by 1 you'll experience at roughly line 105.
instead of working with
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
do work with
seasonal[] s1 = new seasonal[n];
seasonal[] s2 = new seasonal[n];
But when I see code like, this, where you just copy your array:
for (m= 0; m < n; m++)
{
s[m] = seasonal[m];
}
why would you do that? copy the entire array instead of every single entry..
why do you not use any c# constructs?
The problem is this line:
sum += seasonal[j].y;
But there isn't a simple fix. You are creating each object individually through the loop instead of before you enter the loop so each iteration is looking at null objects. Also, the loop this line is in reads past the end of the array. The code is a bit complex to easily see what you're trying to do and how to fix it.
Just an example for to simplify some of your code:
you wrote the following:
if (i>=0 && i<3)
{
seasonal[i].quarter = '1';
}
if (i>=3 && i<6)
{
seasonal[i].quarter = '2';
}
if (i>=6 && i<9)
{
seasonal[i].quarter = '3';
}
if (i>=9 && i<12)
{
seasonal[i].quarter = '4';
}
if (i>12)
{
r = i % 12;
if (r>=0 && r<3)
{
seasonal[i].quarter = '1';
}
if (r>=3 && r<6)
{
seasonal[i].quarter = '2';
}
if (r>=6 && r<9)
{
seasonal[i].quarter = '3';
}
if (r>=9 && r<12)
{
seasonal[i].quarter = '4';
}
}
you could write that instead:
if(i >= 0)
seasonal[i].quarter = (((i % 12)/3) + 1).ToString();
I don' think this code
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
is correct. Try
seasonal[] seas = (seasonal[])Array.CreateInstance(typeof(seasonal), n);