The best magazine
How to Locate a Character in a String
- 1). Enter the following code in the development environment if you are programming in structured query language (SQL):
SELECT CHARINDEX('B', 'ABC')
The SQL CHARINDEX function returns the starting position of the first occurrence of a character within a string. In this example, the function returns two. Keep in mind that the function considers the first character in a string at position one.
If the function cannot locate the character in the string, it returns zero. - 2). Enter the following code in the development environment if you are programming in Microsoft C#:
string stringToSearch = "ABC";
string searchString= "B";
int charLocation = stringToSearch.IndexOf(searchString);
The C# IndexOf method of the String class returns the starting position of the first occurrence of a character within a string. In this example, the method returns one. Keep in mind that the function considers the first character in a string at position zero.
If the function cannot locate the character in the string, it returns negative one. - 3). Enter the following code in the development environment if you are programming in PHP:
<?php
$stringToSearch = "ABC";
print strpos($stringToSearch , "B") . "\n";
?>
stripos() returns the starting position of the first occurrence of a character within a string. In this example, the method returns one. Keep in mind that the function considers the first character in a string at position zero.
If the function cannot locate the character in the string, it returns false. - 4). Enter the following code in the development environment if you are programming in JavaScript:
var stringToSearch = "ABC";
var searchString= "B";
var charLocation = stringToSearch.indexOf(searchString);
The JavaScript indexOf method returns the starting position of the first occurrence of a character within a string. In this example, the method returns one. Keep in mind that the function considers the first character in a string at position zero.
If the function cannot locate the character in the string, it returns negative one.
Source: ...