Store String Character in a Jagged Array - c#

I have a string and want to store every word characters in this string in a jagged array without using a split() method, just loops. I tried this code but it didnt work,i want the result will be something like that:
sepwords[0][1] = {H,e,l,l,o};
sepwords[0][2] = {h,o,w};
sepwords[0][3] = {a,r,e};
sepwords[0][4] = {y,o,u};
The code i tried:
for (int i = 0; i < length; i++)
{
letters[i] = text[i];
}
foreach (char item in letters)
{
for (int i = 0; i < length; i++)
{
if (letters[i] != ',' || letters[i] != ';' || letters[i] != '!' || letters[i] != '?' || letters[i] != '.' || letters[i] != ' ')
{
for (int j = 0; j < length; j++)
{
sepwords[0] = new char[length];
sepwords[0][j] = letters[i];
}
}
else
{
continue;
}
}
}

sepwords[0] = new char[length];
You're overwriting every array with a new one when you reach a new word.

You can simply do this..
char[][] sepwords = new char[4][];
sepwords[0] = "Hello".ToCharArray();
sepwords[1] = "how".ToCharArray();
sepwords[2] = "are".ToCharArray();
sepwords[3] = "you".ToCharArray();

Related

Counting vowels in each line in an array of string C#

I'm writing a code which counts the most frequent word in an array of string , I'm also trying to count the number of vowels in each line of the word , in other words the total number of vowels in all the words which are in the array , I've written the code but it's not working and I can't figure out what's the problem with it , is it because I'm comparing string with char ?
using System;
using System.Collections.Generic;
namespace lab1._2
{
class Program
{
static String findWord(String[] arr)
{
Dictionary<String, int> hs =
new Dictionary<String, int>();
for (int i = 0; i < arr.Length; i++)
{
if (hs.ContainsKey(arr[i]))
{
hs[arr[i]] = hs[arr[i]] + 1;
}
else
{
hs.Add(arr[i], 1);
}
}
String key = "";
int value = 0;
foreach (KeyValuePair<String, int> me in hs)
{
if (me.Value > value)
{
value = me.Value;
key = me.Key;
}
}
return key;
}
static void Main(string[] args)
{
int s;
//char[] v = new char[10] {'a','A','e','E','i','I','o','O','u','U'};
Console.WriteLine("Enter size of array : ");
s = Convert.ToInt32(Console.ReadLine());
string[] arr = new string[s];
Console.WriteLine("Enter string elements : ");
for (int i = 0; i < s; i++)
{
arr[i] = Console.ReadLine();
}
Console.WriteLine("\nArray elements : ");
for (int i = 0; i < s; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("\nThe most frequent word : ");
Console.WriteLine(findWord(arr));
int vowel = 0, cons = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == "a" || arr[i] == "e" || arr[i] == "i" || arr[i] == "o" || arr[i]
== "u")
{
vowel++;
}
else
cons++;
}
Console.WriteLine("Vowels : ");
Console.WriteLine(vowel);
Console.WriteLine("Consants : ");
Console.WriteLine(cons);
}
}
}
I think the problem is that arr is an array of string and you are iterating through it as if it was a single string.
A simple way of doing this would be to have a nested loop.
foreach (var s in arr) // s is a string
{
for (int i = 0; i < s.Length; i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
vowel++;
}
else
cons++;
}
}
https://dotnetfiddle.net/tI3oTc
using System;
public class Program
{
public static void Main()
{
int vowel = 0;
int cons = 0;
string[] arr = new string[]{"test"};
foreach (var s in arr) // s is a string
{
for (int i = 0; i < s.Length; i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
vowel++;
}
else
cons++;
}
}
Console.WriteLine(vowel);
}
}

Issue with infinite loop when reading from file

I am writing a program in C# to read from a file and output to a csv file all of the unique words and the number of occurrences in the file for each word. My issue is when I try to run my program, I never get out of my while loop that goes line by line.
public override List<WordEntry> GetWordCount()
{
List<WordEntry> words = new List<WordEntry>();
WordEntry wordEntry = new WordEntry();
//string[] tokens = null;
string line, temp, getword;
int count = 0, index = 0;
long number;
while ((line = input.ReadLine()) != null)
{
if (line == null)
Debug.Write("shouldnt happen");
char[] delimit = { ' ', ',' };
string[] tokens = line.Split(delimit);
if (words.Count == 0)
{
wordEntry.Word = tokens[0];
wordEntry.WordCount = 1;
words.Add(wordEntry);
}//end if
for (int i = 0; i < tokens.Length; i++)
{
for (int j = 0; j < words.Count; j++)
{
if (tokens[i] == words[j].Word)
{
number = words[j].WordCount;
number++;
getword = words[j].Word;
wordEntry.WordCount = number;
wordEntry.Word = getword;
words.RemoveAt(j);
words.Insert(j, wordEntry);
}//end if
else
{
wordEntry.Word = tokens[i];
wordEntry.WordCount = 1;
words.Add(wordEntry);
}//end else
}//end for
}//end for
}//end while
return words;
}
It is getting stuck in the while loop as if it never reaches the end of the file. The file is 2.6 MB so it should be able to make it to the end.
Here's how you can rewrite your code to use a dictionary.
var words = new Dictionary<string,int>();
while ((line = input.ReadLine()) != null)
{
if (line == null)
Debug.Write("shouldnt happen");
char[] delimit = { ' ', ',' };
string[] tokens = line.Split(delimit);
foreach (var word in tokens)
{
if(words.ContainsKey(word))
words[word]++;
else
words.Add(word, 1);
}
}
This reduces the complexity of the code because dictionary has a O(1) lookup.
EDIT
You can convert the dictionary into List<WordEntry> like this.
return words
.Select(kvp => new WorkEntry
{
Word = kvp.Key,
WordCount = kvp.Value
})
.ToList();
I guess in fact your code doesn't get out of the "for (int j = 0; j < words.Count; j++)" because new items are kept being added to the words list.

how can i fetch text box value in string array and print

this is my code 1 index print second index showing error "Index was outside the bounds of the array." please help what should I do?
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
for (int i = 0; i <= SName.Length - 1; i++)
{
Response.Write(SName[i]);
Response.Write(Email[i]);
}
It is not necessary you get same length for both SName and Email string arrays.
Index is out of bound because length are not same.
Better way is to do it separately:
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
for (int i = 0; i < SName.Length; i++)
Response.Write(SName[i]);
for (int i = 0; i < Email.Length; i++)
Response.Write(Email[i]);
If you want to print one name and email then use this:
string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");
int iLength = -1;
if(SName.Length > Email.Length)
iLength = SName.Length;
else
iLength = Email.Length;
for (int i = 0; i < iLength; i++)
{
if(i < SName.Length)
Response.Write(SName[i]);
if(i < Email.Length)
Response.Write(Email[i]);
}
NOTE:
If you are not dealing with array of HTML element with same name then you don't have to use Request.Form.GetValues("title"). See following example:
string SName = Request.Form["title"];
string Email = Request.Form["fname"];
Response.Write(SName + " " + Email);
Your code should be.
if (SName != null)
for (int i = 0; i < SName.Length; i++)
Response.Write(SName[i]);
if (Email != null)
for (int i = 0; i < Email.Length; i++)
Response.Write(Email[i]);
The problem is that length of SName and Email are different.
You can use the below code, which gives the result in a single loop
if (SName != null && SName.Length > 0 && Email != null && Email.Length > 0)
{
for (int i = 0,j=0; i < SName.Length && j<Email.Length; i++,j++)
{
Response.Write(SName[i]);
Response.Write(Email[j]);
}
}

.NET C# Logic Function, recurrent function

I have some string in format like that
XXXX-XXXX-X_X_
All "_" should be replaced with Letters and numberst to prodce sth like that:
XXXX-XXXX-XAXA
XXXX-XXXX-XAXB
XXXX-XXXX-XAXC
XXXX-XXXX-XAXD
XXXX-XXXX-XAXE
XXXX-XXXX-XAXF
XXXX-XXXX-XAXG
(...)
XXXX-XXXX-XZX8
XXXX-XXXX-XZX9
XXXX-XXXX-X0XA
(...)
XXXX-XXXX-X2XA
XXXX-XXXX-X2XB
I know hoe to make it with one "_".
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
foreach (char letter in alphaLetters.ToCharArray())
{
Numbers.Add(number.Replace('_', letter)));
}
I want this code to be working with unknown number of "_".
Can you help?
IMHO it must be recursive. (Note: that does not mean it must use recursive method call, although I used recursive call in the following code, it can be easily converted to internal recursion stack. )
public static void RunSnippet()
{
var r = new List<string>();
Replace("asd_asd_asd_".ToCharArray(), 0, r);
foreach(var s in r) { Console.WriteLine(s); }
}
public static char[] possibilities = new char[] { 'A', 'B', 'C' };
public static void Replace(char[] chars, int startIndex, IList<string> result)
{
for (int i = startIndex; i < chars.Length; i++)
{
if (chars[i] != '_')
{
continue;
}
// we found first '_'
for (int j = 0; j < possibilities.Length; j++)
{
chars[i] = possibilities[j];
Replace(chars, i + 1, result);
}
chars[i] = '_'; // take back what we replaced
return; //we're done here
}
// we didn't find any '_', so all were replaced and we have result:
result.Add(new string(chars));
}
Try this one:
var alphaIndexes = new List<int>();
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
for(int n = 0; n<Numbers.Count; n++) {
char[] numberLetters = Numbers[n].ToCharArray();
int position = 0;
for(int i = numberLetters.Length - 1; i>=0; i--) {
if(numberLetters[i] == '_') {
int alphaIndex = 0;
if(alphaIndexes.Count <= position)
alphaIndexes.Add(0);
else {
alphaIndex = alphaIndexes[position];
}
numberLetters[i] = alphaLetters[alphaIndex];
position++;
}
}
if(alphaIndexes.Count > 0) {
alphaIndexes[0]++;
for(int j = 0; j < alphaIndexes.Count; j++) {
if(alphaIndexes[j] >= alphaLetters.Length) {
alphaIndexes[j] = 0;
if (j < alphaIndexes.Count)
alphaIndexes[j+1]++;
}
}
}
Numbers[n] = new String(numberLetters);
Numbers[n].Dump();
}

How to split a deliminated string with encapsulation and escapes

I would like to split a string deliminated by a character such as ‘&’, but in the case where some values contain the deliminator I would like to escape with double quotes. What is an elegant approach to splitting while ignoring the deliminating characters that have been escaped while also accounting for escape character escapes?
For example split this string properly
var1=asdfasdf&var2=contain””quote&var3=”contain&delim”&var4=”contain””both&”
Into:
var1=asdfasdf
var2=contain"quote
var3=contain&delim
var4=contain"both&
Incidentally, I am thinking Regex...
My solution, with test:
void TestCharlesParse()
{
string s = #"var1=asdfasdf&var2=contain""""quote&var3=""contain&delim""&var4=""contain""""both&""";
string[] os = CharlesParse(s);
for (int i = 0; i < os.Length; i++)
System.Windows.Forms.MessageBox.Show(os[i]);
}
string[] CharlesParse(string inputString)
{
string[] escapedQuotes = { "\"\"" };
string[] sep1 = inputString.Split(escapedQuotes, StringSplitOptions.None);
bool quoted = false;
ArrayList sep2 = new ArrayList();
for (int i = 0; i < sep1.Length; i++)
{
string[] sep3 = ((string)sep1[i]).Split('"');
for (int j = 0; j < sep3.Length; j++)
{
if (!quoted)
{
string[] sep4 = sep3[j].Split('&');
for (int k = 0; k < sep4.Length; k++)
{
if (k == 0)
{
if (sep2.Count == 0)
{
sep2.Add(sep4[k]);
}
else
{
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep4[k];
}
}
else
{
sep2.Add(sep4[k]);
}
}
}
else
{
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep3[j];
}
if (j < (sep3.Length-1))
quoted = !quoted;
}
if (i < (sep1.Length - 1))
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + "\"";
}
string[] ret = new string[sep2.Count];
for (int l = 0; l < sep2.Count; l++)
ret[l] = (string)sep2[l];
return ret;
}

Categories