I am trying to write a code to merge two string based on index of character.For e.g-If we have two string "abc" and "defg",I want a string output1(merging all even character of both strings)="adcf" and another string output2="beg" (remaining all words).
What I tried-
class Program
{
static void Main(string[] args)
{
string a= "First";
string b= "MiddleName";
string newstring = "";
string newstring1 = "";
int length = b.Length;
for (int l = 0; l < length; l=l+1)
{
if(l%2==0)
{
newstring = newstring + a[l].ToString() + b[l].ToString();
}
if (l % 2 == 1)
{
newstring1 = newstring1 + a[l].ToString() + b[l].ToString();
}
}
Console.ReadLine();
}
}
But then in this case it will give outside the bound array exception.Any better way to do this?
Thanks
I suggest extracting a method where you should solve the generalized problem of merging two strings taking each step characters from them starting from offset:
private static String Merge(String left, String right, int step, int offset) {
StringBuilder sb = new StringBuilder();
if (null == left)
left = ""; // or throw exception
if (null == right)
right = ""; // or throw exception
for (int i = offset; i < Math.Max(left.Length, right.Length); i += step) {
//DONE: do not forget to check if you can get a character
if (i < left.Length)
sb.Append(left[i]);
//DONE: do not forget to check if you can get a character
if (i < right.Length)
sb.Append(right[i]);
}
return sb.ToString();
}
And so you can put it
String a = "abc";
String b = "defg";
// adcf
String output1 = Merge(a, b, 2, 0);
// beg
String output2 = Merge(a, b, 2, 1);
it happens because B has longer words than A. So when its iteration is bigger than A' length, it will cause an error.
so you need to check whether A has that much word, before adding it
IF B' length always greater than A, then you can use bellow code
class Program
{
static void Main(string[] args)
{
string a= "First";
string b= "MiddleName";
string newstring = "";
string newstring1 = "";
int length = b.Length;
for (int l = 0; l < length; l=l+1)
{
if(l%2==0)
{
if(a.Length > l)
{newstring += a[l].ToString();}
newstring += b[l].ToString();
}
if (l % 2 == 1)
{
if(a.Length > l)
{newstring1 += a[l].ToString();}
newstring1 += b[l].ToString();
}
}
Console.ReadLine();
}
}
for (int l = 0; l < b.length && l < a.length; l++)
{
if(l%2==0)
{
newstring += a[l]+ b[l];
}
if (l % 2 == 1)
{
newstring1 += a[l] + b[l];
}
}
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
I am trying to solve the coding problem below:
Given a dictionary of words
And user entered word to compare against
When comparing the given word against the dictionary
Then output all words in the dictionary that exist in the given word
E.g. StartBurst would output Star and Burst if those words were in the dictionary.
Below is my code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string w = Console.ReadLine();
string[] dictionary = new string[106];
{
string word = w;
string word2 = w;
string w1 = word;
string w2 = word2;
for (int n = 0; n < w.Length; n++)
{
w1 = word;
w2 = word;
for (int x = 0; x < word.Length; x++)
{
for (int i = 0; i < dictionary.Length; i++)
{
if (w1.Equals(dictionary[i]) && w1 != w2)
{
Console.WriteLine(w1);
Console.ReadLine();
}
if (w2.Equals(dictionary[i]) && w1 != w2)
{
Console.WriteLine(w2);
Console.ReadLine();
}
}
w1 = w1.Substring(1, w1.Length - 1);
w2 = word.Substring(0, word.Length - x);
}
word = word.Substring(1, word.Length - 1);
}
}
}
}
}
However, when I run this, it outputs far too much output. For example, if I enter "dontdo" the program outputs "dont do do do do do do". I believe this is due to the word = word.Substring(1, word.Length - 1); statement, but I am unsure how to rectify the situation. Can anyone help?
I created a small code snippet for you to find all the substrings that you need in your search.
void Main()
{
foreach(var w in createMatchables("real"))
{
Console.WriteLine(w);
}
}
// this creates all the searchable substrings from a given string
// all the strings are created from left to right
List<string> createMatchables(string str)
{
var matchList = new List<string>();
for (int i = str.Length; i != 0; i--)
{
var branchCount = str.Length / i;
for (int j = 0; j < branchCount; j++)
{
matchList.Add(str.Substring(i*j, i));
}
}
return matchList;
}
I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');
I am trying to read the data in a text file which is separated by commas. My problem, is that one of my data pieces has a comma within it. An example of what the text file looks like is:
a, b, "c, d", e, f.
I want to be able to take the comma between c and d and change it to a semicolon so that I can still use the string.Split() method.
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine ()) != null) {
bool firstQuote = false;
for (int i = 0; i < line.Length; i++)
{
if (line [i] == '"' )
{
firstQuote = true;
}
else if (firstQuote == true)
{
if (line [i] == '"')
{
break;
}
if ((line [i] == ','))
{
line = line.Substring (0, i) + ";" + line.Substring (i + 1, (line.Length - 1) - i);
}
}
}
Console.WriteLine (line);
}
I am having a problem. Instead of producing
a, b, "c; d", e, f
it is producing
a, b, "c; d"; e; f
It is replacing all of the following commas with semicolons instead of just the comma in the quotes. Can anybody help me fix my existing code?
Basically if you find a closing " you recognize it as it was an opening quote.
Change the line:
firstQuote = true;
to
firstQuote = !firstQuote;
and it should work.
You need to reset firstquote to false after you hit the second quote.
else if (firstQuote == true) {
if (line [i] == '"') {
firstquote = false;
break;
}
Here is a simple application to get the required result
static void Main(string[] args)
{
String str = "a,b,\"c,d\",e,f,\"g,h\",i,j,k,l,\"m,n,o\"";
int firstQuoteIndex = 0;
int secodQuoteIndex = 0;
Console.WriteLine(str);
bool iteration = false;
//String manipulation
//if count is even then count/2 is the number of pairs of double quotes we are having
//so we have to traverse count/2 times.
int count = str.Count(s => s.Equals('"'));
if (count >= 2)
{
firstQuoteIndex = str.IndexOf("\"");
for (int i = 0; i < count / 2; i++)
{
if (iteration)
{
firstQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
}
secodQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
string temp = str.Substring(firstQuoteIndex + 1, secodQuoteIndex - (firstQuoteIndex + 1));
firstQuoteIndex = secodQuoteIndex + 1;
if (count / 2 > 1)
iteration = true;
string temp2= temp.Replace(',', ';');
str = str.Replace(temp, temp2);
Console.WriteLine(temp);
}
}
Console.WriteLine(str);
Console.ReadLine();
}
Please feel free to ask in case of doubt
string line = "a,b,mc,dm,e,f,mk,lm,g,h";
string result =replacestr(line, 'm', ',', ';');
public string replacestr(string line,char seperator,char oldchr,char newchr)
{
int cnt = 0;
StringBuilder b = new StringBuilder();
foreach (char chr in line)
{
if (cnt == 1 && chr == seperator)
{
b[b.ToString().LastIndexOf(oldchr)] = newchr;
b.Append(chr);
cnt = 0;
}
else
{
if (chr == seperator)
cnt = 1;
b.Append(chr);
}
}
return b.ToString();
}
I need a method that returns every other character in a string starting with the first character. For example, a method call with ("Java-language") returns "Jv-agae."
private static void NewMethod(string word)
{
// here comes the code
}
var str = "Java-language";
var xx = new string(str.Where((ch, index) => index % 2 == 0).ToArray());
Console.WriteLine(xx);
Or this one:
var xx = string.Join<char>("", str.Where((ch, index) => (index & 1) == 0));
probably little different then everybody else: :-)
protected static IEnumerable<char> EverySecondChar(string word)
{
for(int i = 0; i < word.Length; i += 2)
yield return word[i];
}
string result = new string(EverySecondChar("Java-language").ToArray());
Here is my suggestion for you:
private string TakeEverySecondChar(string input)
{
var result = string.Empty;
for (int i = 0; i < input.Length; i+=2)
{
result += input.Substring(i, 1);
}
return result;
}
Console.Clear();
string Lang = "Java-language";
string[] LangArr = new string[Lang.Length];
char LangChar;
for (int i = 0; i < Lang.Length; i++)
{
LangChar = Lang[i];
LangArr[i] = LangChar.ToString();
}
for (int i = 0; i < LangArr.Length; i++)
{
Console.Write(LangArr[i]);
i++;
}
Console.ReadLine();
public String strip2ndchar(string text)
{
string final="";
int i = 0;
foreach (char a in text.ToCharArray())
{
if (i % 2 == 0)
final += a;
i++;
}
return final;
}