Hi Guys
NP80 compared with -1
In this program why it should compared with -1. “if (-1 != s.IndexOf("COM"))”.
Please explain the reason.
Thank you
using System;
class Foreach
{
// Digging into an array using foreach.
public static int
{
string[] arrBookTitles = new string[] { "Complex Algorithms",
"COM for the Fearful Programmer",
"Do you Remember Classic COM?",
"C# and the .NET Platform",
"COM for the Angry Engineer" } ;
int COM = 0, NET = 0;
// Assume we are not looking for books on COM interop.
foreach (string s in arrBookTitles)
{
if (-1 != s.IndexOf("COM"))
COM++;
else if(-1 != s.IndexOf(".NET"))
NET++;
}
Console.WriteLine("Found {0} COM references and {1} .NET references.",
COM, NET);
return 0;
}
}
/*
Found 3 COM references and 1 .NET references.
*/
Posted Feb 6, 2008, 6:31 PM
Thank you for your explanation, Alan.
AlanPosted Feb 6, 2008, 4:51 PM
s.IndexOf("ever") always returns -1 because "ever" is not contained within any of the strings in the arrBookTitles array.
Consequently, the variable 'ever' is never incremented and remains at its original value of 0.
Posted Feb 6, 2008, 4:21 PM
I altered the above program for better understanding. According to the above explanation out put of the altered program must be -1 but program is producing 0. Please explain the reason.
using System;
class Foreach
{
// Digging into an array using foreach.
public static intMain (string[] args)
{
string[] arrBookTitles = new string[] { "aaa", "www", "rrr", "xxx" };
int ever = 0;
foreach (string s in arrBookTitles)
{
if (-1 != s.IndexOf("ever"))
ever++;
}
Console.WriteLine(ever);
return 0;
}
}
/*
0
*/
AlanPosted Feb 6, 2008, 9:50 AM
The s.IndexOf(t) method returns the index (starting from 0) of the first occurrence of the string 't' within the string 's'.
So, if s == "never" and t == "ever", the method would return 1.
If 't' cannot be found, then the method returns a value of -1.
So, in this line:
if (-1 != s.IndexOf("COM"))
the code within the 'if' statement is only executed if "COM" is contained within the string 's'.