C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example: IndexOf returns the location of the string "dog." It is not equal to -1. So the line is written to the console window.
Note: Usually we want to know the exact result of IndexOf. We can store its result in an int local.
C# program that uses IndexOf
using System;
class Program
{
static void Main()
{
// The input string.
const string value = "Your dog is cute.";
// Test with IndexOf method.
if (value.IndexOf("dog") != -1)
{
Console.WriteLine("string contains dog!");
}
}
}
Output
string contains dog!
While: We call IndexOf within a while-statement. We test it for success each time. If the character is not found, the loop ends.
WhileArgument 1: The first argument to IndexOf here is the character we are searching for—in this case the lowercase letter "a."
Argument 2: This is the start index we want to search from in the source string. With the initial value 0, we begin at the first char.
Warning: We must advance past the current character by adding 1 to the index. If we do not do this, we will get an infinite loop.
C# program that uses IndexOf in loop
using System;
class Program
{
static void Main()
{
// The input string.
string s = "I have a cat";
// Loop through all instances of the letter a.
int i = 0;
while ((i = s.IndexOf('a', i)) != -1)
{
// Print out the substring.
Console.WriteLine(s.Substring(i));
// Increment the index.
i++;
}
}
}
Output
ave a cat
a cat
at
So: Please be careful when using IndexOf. It is probably better to check for negative one at least once in most places.
C# program that shows IndexOf return value
using System;
class Program
{
static void Main()
{
string source = "big dog";
// See result of IndexOf method.
Console.WriteLine("NOT FOUND: {0}", source.IndexOf("cat"));
Console.WriteLine("FOUND: {0}", source.IndexOf("dog"));
}
}
Output
NOT FOUND: -1
FOUND: 4
Info: The Substring method returns the rest of the string starting at a specified number.
SubstringC# program that uses Substring
using System;
class Program
{
static void Main()
{
// Input.
const string s = "I have a cat";
// Location of the letter c.
int i = s.IndexOf('c');
// Remainder of string starting at c.
string d = s.Substring(i);
Console.WriteLine(d);
}
}
Output
cat
C# program that skips start characters
using System;
class Program
{
static void Main()
{
string value = ":100,200";
// Skip the first character with a startIndex of 1.
int comma = value.IndexOf(',', 1);
Console.WriteLine(comma);
}
}
Output
4
Version 1: Here we use a single-character iteration for-loop. We see the "for" and "if" keywords in the code.
Version 2: This version of the code uses the IndexOf() method with a single char argument to search a string.
Result: It is more efficient to scan each character individually than to use IndexOf.
Note: The internal code for IndexOf is more complex—it is harder to optimize for the compiler.
C# program that times for-loop, IndexOf
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
string s = "abc.123.456.xyz";
// Version 1: use for-loop to count chars.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int c = 0;
for (int e = 0; e < s.Length; e++)
{
if (s[e] == '.')
{
c++;
}
}
}
s1.Stop();
// Version 2: use IndexOf to count chars.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int c = 0;
int e = 0;
while ((e = s.IndexOf('.', e)) != -1)
{
e++;
c++;
}
}
s2.Stop();
// Result times.
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
18.21 ns: For-loop
26.78 ns: IndexOf, while-loop
Version 1: Here we invoke IndexOf with a char argument. We use a char instead of a string, but the output is the same.
Version 2: This version of the code calls IndexOf with a single-character string argument.
Result: The string IndexOf will require more CPU cycles. And even if we pass in StringComparison.Ordinal, it is slower.
So: A char argument is more efficient. Using a string is many times slower than using a char value.
C# program that times IndexOf, char versus string
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
string value = "The puppy is adorable.";
// Version 1: use char argument.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result = value.IndexOf('a');
}
s1.Stop();
// Version 2: use string argument.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result = value.IndexOf("a");
}
s2.Stop();
// Result times.
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
13.07 ns: IndexOf char argument
226.86 ns: IndexOf string argument
Note: This method is similar to calling IndexOf several times with the logical OR operator.
However: IndexOfAny has different performance characteristics. It may result in clearer code.
Return: LastIndexOf also returns -1 if the argument cannot be located. So it is the same except for search order.
Note: The IndexOf method is actually a FirstIndexOf method. The name just omits the First.
Internals: If Contains' internal IndexOf returns -1, Contains returns false. Otherwise it returns true.