开发者

Finding the signs from a string Java

Is there a function or something, that is开发者_开发知识库 made for finding the signs in a String (e.g. +/-[]{})(). If there is such a thing, please tell or if not, just to know to start typing code myself.


String line = "+-/[]{}()";
line.indexOf("+"); // if >= 0, character exists, if < 0, character does not exist in string.


If I understand it correctly you want to know where in the string + or - are.

To do this you need to search through the string checking for the characters you are looking for. The function below will return you 0-based indexes for the locations of the character in the string.

public List<Integer> getLocationsOfChar(String input, char c) { 
    List<Integer> locations = new ArrayList<Integer>();
    int index = -1;
    int startAt = 0;
    while ((index = input.indexOf(c, startAt)) != -1) {
        locations.add(index);
        startAt = index+1;
    }
    return locations;
}

To use this you would call:

List<Integer> locs = getLocationsOfChar("abgc+sda-+", '+')

In this example the list locs would contain 4, 9.

When no items are present, the list returned would be empty.


You could also use a regular expression.

Check this out too:

String API

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜