1

In Java, given a string, like "abc@df" where the character '@' could be ANY other non-letter, like '%', '^', '&', etc. What would be the most efficient way to find that index? I know that a for loop would be kind of quick (depending on the string length), but what about any other quicker methods? A method that finds all index(es) of non-alphabetical letters or the closest one to a given index (like indexOf(string, startingIdx)) Thanks!

Jsbbvk
  • 180
  • 2
  • 19
  • 1
    If you look at the implementation of indexOf, I'd be willing to bet you'd find a loop. The advantage of using it would be that you don't have to write the loop, and that's a good thing because best code is code that you don't write. – BillRobertson42 Oct 28 '17 at 02:57
  • @Bill I think I didn't clarify. Find a way to find an index of a non-alphabetic character. Since there is a huge range of non-alphabetical characters, it's not possible to use indexOf() because you don't specifically know the character you are looking for. Hope this helps! – Jsbbvk Oct 28 '17 at 03:04
  • Sure I get that, which is part of the reason that I left a comment instead of suggesting an answer. – BillRobertson42 Oct 28 '17 at 03:11

4 Answers4

1

A for loop, you can use the Character class to determine if each character is a Letter (or other type). See: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isAlphabetic(int)

Nicholas Hirras
  • 2,592
  • 2
  • 21
  • 28
0

You should probably use a regular expression:

  Pattern patt = Pattern.compile("[^A-Za-z]");
  Matcher mat = patt.matcher("avc@dgh");
  boolean found = mat.find();
  System.out.println(found ? mat.start() : -1);
user184994
  • 17,791
  • 1
  • 46
  • 52
0

You could use regex to split the string on anything that is not alphabetic:

String str = "abc@df"; 
String[] split = str.split("[^A-za-z]");

Then you can use the length of the strings in that array to find the index of the non - alphabetic chars:

int firstIndex = split[0].length();

And so on:

int secondIndex = firstIndex + split[1].length();
awskme
  • 11
  • 2
0

I realize that this is old, however a couple of the regex answers above specified [^A-za-z], however I expect they intended to say [^A-Za-z], otherwise it would include a handful of non-alpha characters in the range including [, , ], ^, etc...

Bill
  • 31
  • 1