I have written a function to find the the line by searching the text and after it find that particular line, I want to read the next line and return that text. The function is as follows:
public static string NextString(string textfind)
{
List<string> found = new List<string>();
string linejd;
using (StreamReader efile = new StreamReader(FILENAME))
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null)
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
return nextstring;
}
}
}
}
File name has been defined as:
const string FILENAME = #"E:\model\Yen and Lee\AQRun01\eratc.inp";
However, I keep on getting error:
AQ.Program.NextString(string)': not all code paths return a value
What if in your function above, your code doesn't enter the loop or the if (linejd.Contains(textfind)) block? The function returns no value!
I tend to recommend declaring a function's result variable and setting its value within the function and then returning it at the end:
static public string nextstring(string textfind)
{
string result = string.Empty;
List<string> found = new List<string>();
string linejd;
/* ********************************************************
* Find the line with certain string */
using (StreamReader efile = new StreamReader(FILENAME))
// using (efile)
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null
&& string.IsNullOrWhiteSpace(result)) // Quit the loop once we have a result!
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
result = nextstring; }
}
}
return result;
}
If the condition linejd.Contains(textfind) is never true then the function will never return anything, yet the function declaration states that it will return a string. You can fix this by returning a default value (such as an empty string) after the using block.
There are two reasons to why the function could exit without a return value:
The file is empty, so the while loop is never entered.
The condition linejd.Contains(textfind) is never true.
Even if you know that the file is never empty, and that the string can always be found in the file, the compiler doesn't know that. (Although, the while loop doesn't make sense if you know that the string can always be found, as that means that you will never reach the end of the file.)
You need to tell the compiler what to do for both those cases, for example by adding return null; at the end of the function.
Alternatively rewrite the code so that it actually relies on the file always containing something and that the string is always found. That way there is no loose ends to take care about. That of course means that the code will crash or hang if the file actually would be empty or the string is not found.
How about using Linq?
public static string NextString(string textfind)
{
return File.ReadLines(FILENAME)
.SkipWhile(line => !line.Contains(textfind))
.Skip(1)
.First();
}
when the if case is always fault, then your method will return nothing.. That's why you get an error.
try writing a return value before the end of your method like:
public static string NextString(string textfind)
{
List<string> found = new List<string>();
string linejd;
string new_string = string.Empty;
using (StreamReader efile = new StreamReader(FILENAME))
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null)
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
return nextstring;
}
}
}
return (new_string);
}
Related
I have a dictionary of all alphabets mapped to morse code
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("a", ".-");
data.Add("b", "-...");
data.Add("c", "-.-.");
data.Add("d", "-..");
data.Add("e", ".");
data.Add("f", "..-.");
data.Add("g", "--.");
data.Add("h", "....");
data.Add("i", "..");
data.Add("j", ".---");
data.Add("k", "-.-");
data.Add("l", ".-..");
data.Add("m", "--");
data.Add("n", "-.");
data.Add("o", "---"); and so on..
I'm trying to check on a condition if the substring of an existing morse code exists in the dictionary or not.
foreach (var item in arraylist)
{
int smallcount=0;
int startIndex = 0;
//check if this combination exists for morse code
for(int w=0;w<shortInput;w++)
{
int substringLength=Convert.ToInt32(item[w].ToString());
string sub = morsecode.Substring(startIndex, substringLength);
if (data.ContainsValue(sub)) ;
{
smallcount++;
}
startIndex = startIndex + substringLength;
}
if(smallcount==shortInput)
{ count++; }
}
Here data.ContainsValue(sub) always returns true even if the value does not exist in the dictionary.
Can anyone tell me if i'm missing anything.?
ContainsValue is not actually returning true, however you have a stray semicolon after the if statement. This means that the following block will always be executed, as it is not executed conditionally. It gets treated as follows:
if (data.ContainsValue(sub))
{
}
{
smallcount++;
}
Instead, remove the semicolon so that you actually have a block directly following the if statement, like so:
if (data.ContaisnValue(sub))
{
smallcount++;
}
I have declared a method in a class to compare two numbers and I'm having an issue. I'm getting an error saying not all code paths return a value. I want to return an int for every matching number in the char arrays.
Here is an image of the code.
public int CompareCodes(string rndselect, string personselect)
{
char[] rndnumber = rndselect.ToCharArray(); //take the randoms elected one and convert it to a char array
char[] perNum = personselect.ToCharArray();
likeness0 = 0;
likeness1 = 1;
foreach (char RndNum in rndnumber)
{
foreach (char Pnum in perNum)
{
if (RndNum == Pnum)
{
return likeness1;
}
else
{
return likeness0;
}
}
}
}
What should compiler think if your perNum is empty?
The error says exactly what is wrong with your code. Having a foreach loop doesn't guarantee anything inside the foreach is executed. If rndnumber or perNum happens to be empty, there is nothing to loop through and your code actually doesn't return anything.
If rndselect or perNum is empty string.
So no value is returned.
If you sure these string are always not null. so add
return 0
at the end of block.
I am trying to extract the number out of the last part of the string, I have wrote a function to do this but am having problems with out of range index.
Here is the string
type="value" cat=".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.1" descCat=".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3"
and here is my function
private static string ExtractDescOID(string property)
{
string result = "";
int startPos = property.LastIndexOf("descOid=\"") + "descOid=\"".Length;
int endPos = property.Length - 1;
if (endPos - startPos != 1)
{
//This now gets rid of the first . within the string.
startPos++;
result = property.Substring(startPos, endPos);
}
else
{
result = "";
}
if (startPos == endPos)
{
Console.WriteLine("Something has gone wrong");
}
return result;
}
I want to be able to get 1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3 this part of the string. I have stepped through the code, the string length is 99 however when AND MY startPos becomes 64 and endPos becomes 98 which is actually within the range.
The second argument to Substring(int, int) isn't the "end position", but the length of the substring to return.
result = property.Substring(startPos, endPos - startPos);
Read the documentation again, the second value is the length, not the index.
As found on MSDN:
public string Substring(
int startIndex,
int length
)
A different approach to this problem could be through using string.Split() to take care of the parsing for you. The only reason why I would propose this (other than that I like to present additional options to what's already there, plus this is the lazy man's way out) is that from a code perspective, the code is easier IMHO to decompose, and when decomposed, is easier to comprehend by others.
Here's the sample program with some comments to illustrate my point (tested, btw).
class Program
{
static void Main(string[] args)
{
var someAttributesFromAnXmlNodeIGuess =
"type=\"value\" cat=\".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.1\" descCat=\".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3\"";
var descCat = GetMeTheAttrib(someAttributesFromAnXmlNodeIGuess, "descCat");
Console.WriteLine(descCat);
Console.ReadLine();
}
// making the slightly huge assumption that you may want to
// access other attribs in the string...
private static string GetMeTheAttrib(string attribLine, string attribName)
{
var parsedDictionary = ParseAttributes(attribLine);
if (parsedDictionary.ContainsKey(attribName))
{
return parsedDictionary[attribName];
}
return string.Empty;
}
// keeping the contracts simple -
// i could have used IDictionary, which might make sense
// if this code became LINQ'd one day
private static Dictionary<string, string> ParseAttributes(string attribLine)
{
var dictionaryToReturn = new Dictionary<string, string>();
var listOfPairs = attribLine.Split(' '); // items look like type=value, etc
foreach (var pair in listOfPairs)
{
var attribList = pair.Split('=');
// we were expecting a type=value pattern... if this doesn't match then let's ignore it
if (attribList.Count() != 2) continue;
dictionaryToReturn.Add(attribList[0], attribList[1]);
}
return dictionaryToReturn;
}
}
I am trying to convert an int var to a string var for use in a .txt file. i am coming up with a "unassigned local variable error". I have looked thru other questions but i don't see what i am missing. I have been able to convert int var to a string var before, i am not really sure where i am going wrong. If you could also give me the theory with the solution it would be most helpfull
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
if (BTSBtn.Checked)
{
sbntmsk = 30;
}
string subntmsk;
subntmsk = sbntmsk.ToString();
The compiler has no way to know if your checkboxes will be checked at runtime and so it complains because there is a possibility that the variable sbntmsk reaches the point where you try to convert it to a string without having a value assigned.
To fix the message declare and initialize sbntmsk with (or whatever default value you like)
int sbntmsk = 0;
You need to provide a default value for the integer. For example, what would you expect to be in the string if neither button was checked?
You could just use strings?
var sbntmsk = String.Empty;
if (RBSBtn.Checked)
{
sbntmsk = "29";
}
if (BTSBtn.Checked)
{
sbntmsk = "30";
}
Try using this approach:
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
else if (BTSBtn.Checked) // Notice the ELSE - IF
{
sbntmsk = 30;
}
else
{
sbntmsk = 0; // a default value
}
string subntmsk = String.Empty; // initialize with empty
subntmsk = sbntmsk.ToString();
Since using multiple checkboxes you are assigning to a same variable so no need to check all IF blocks. Also, using this way you have a possibility to define an 'ELSE' block at the end.
Hope it helps!
I want to compare whether two strings are equal or not in C# using the Equals() method of the string class. But even though both strings are same, my conditional check is failing.
I have seen that both strings are equal and also verified this at the http://text-compare.com/ site. I don't know what is the issue here...
My code is :
protected string getInnerParaOnly(DocumentFormat.OpenXml.Wordprocessing.Paragraph currPara, string paraText)
{
string currInnerText = "";
bool isChildRun = false;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(currPara.OuterXml);
XmlNode newNode = xDoc.DocumentElement;
string temp = currPara.OuterXml.ToString().Trim();
XmlNodeList pNode = xDoc.GetElementsByTagName("w:p");
for (int i = 0; i < pNode.Count; i++)
{
if (i == 0)
{
XmlNodeList childList = pNode[i].ChildNodes;
foreach (XmlNode xNode in childList)
{
if (xNode.Name == "w:r")
{
XmlNodeList childList1 = xNode.ChildNodes;
foreach (XmlNode xNode1 in childList1)
{
if (xNode1.Name == "w:t" && xNode1.Name != "w:pict")
{
currInnerText = currInnerText + xNode1.InnerText;
}
}
}
}
if (currInnerText.Equals(paraText))
{
//do lot of work here...
}
}
}
When I put a break point in and go through step by step, watching each and every character, then there is a difference in currInnerText last index. It looks like an empty char. But I already used the Trim() function. This is the picture captured during the debug process.
What is the solution for removing the empty char or any other spurious characters at the end of the currInnerText string?
Try this
String.Equals(currInnerText, paraText, StringComparison.InvariantCultureIgnoreCase);
In my case, the difference was different encoding of space character, one string contained non-breaking space (160) and the other one contained normal space (32)
it can be solved by
string text1 = "String with non breaking spaces.";
text1 = Regex.Replace(text1, #"\u00A0", " ");
// now you can compare them
Try putting a breakpoint and checking the length. Also, in some cases, if the locale is not the same, the equals function does not result in true. Another method you could try(checking the length) is printing both like this ---string1---, ---string2---, this way, you could see if you have any trailing spaces. To fix this you can use string1.trim()
Before you call .Equals, try this:
if (currInnerText.Length != paraText.Length)
throw new Exception("Well here's the problem");
for (int i = 0; i < currInnerText.Length; i++) {
if (currInnerText[i] != paraText[i]) {
throw new Exception("Difference at character: " + i+1);
}
}
That should throw an exception if Equals returns false and should give you an idea what's going.
In addition to using characters that look like other characters, but are actually different, this can occur when using Reflection. Reflection boxes the values twice into new objects and == will compare by reference. Try using object.Equals(currentValue, newValue) instead.