Indexes of all occurrences of character in a string
This should print the list of positions without the -1
at the end that Peter Lawrey's solution has had.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
It can also be done as a for
loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[Note: if guess
can be longer than a single character, then it is possible, by analyzing the guess
string, to loop through word
faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
More efficient way to get all indexes of a character in a string
You can use String.IndexOf
, see example below:
string s = "abcabcabcabcabc";
var foundIndexes = new List<int>();
long t1 = DateTime.Now.Ticks;
for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))
{
// for loop end when i=-1 ('a' not found)
foundIndexes.Add(i);
}
long t2 = DateTime.Now.Ticks - t1; // read this value to see the run time
How to find all occurrences of a substring?
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer
returns a generator, so you could change the []
in the above to ()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
Finding all indexes of a specified character within a string
A simple loop works well:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
if (str[i] === "s") indices.push(i+1);
and now it will give you your expected result.
A fiddle can be see here.
I don't think looping through the whole is terribly efficient
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.
How to get indexes of char in the string
I assume you want to get m2rh5b7
from your input string Merhaba
based on your code, then the below works fine,
String input = "Merhaba";
StringBuilder output = new StringBuilder();
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
output.append(i+1);
} else {
output.append(c);
}
}
System.out.println(output); // prints --> m2rh5b7
Or if you want just position of the vowels position only, the below is fine,
String input = "Merhaba";
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
System.out.println(i);
}
}
you can use regex also, please refer the above from Alias.
Find all occurrences of a character in a String
One way to do this is to find the indices using list comprehension:
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
output:
[2, 3]
Related Topics
Pylab.Ion() in Python 2, Matplotlib 1.1.1 and Updating of the Plot While the Program Runs
In Pytest, What Is the Use of Conftest.Py Files
How to Activate a Virtualenv Inside Pycharm's Terminal
How to Make a Selenium Script Undetectable Using Geckodriver and Firefox Through Python
Adding a Background Image to a Plot
Python Webbrowser.Open() to Open Chrome Browser
How to Load a Module from Code in a String
Optimal Hdf5 Dataset Chunk Shape for Reading Rows
Calculate Area of Polygon Given (X,Y) Coordinates
What Is Python Whitespace and How Does It Work
Peak-Finding Algorithm for Python/Scipy
How to Use Multiprocessing Queue in Python
How to Generate a Random Number with a Specific Amount of Digits
Python: How to Get Stdout After Running Os.System
What Is the Most Pythonic Way to Pop a Random Element from a List