How to get the next occurence of a character in Java?

Posted on 2012-08-30
Last Modified: 2012-08-30
If I have a string such as abc.def.ghi.jkl.mno

I want to be able to get substrings from the first occurence of  "." to the next occurence of "."
Question by:akashsuresh
    LVL 16

    Expert Comment

    Use StringTokenizer.
    LVL 86

    Assisted Solution

    In one line
    s = s.replaceAll(".*?\\.([^.]+).*", "$1");

    Open in new window

    s = s.split("\\.")[1];// poss less efficient

    Open in new window

    else use charAt and substring
    LVL 1

    Author Comment

    Could you explain how to do it with charAt and substring?
    LVL 86

    Accepted Solution

    int dotPos = s.indexOf('.');
    if (dotPos >= 0) {
       String temp = s.substring(dotPos);
        dotPos = temp.indexOf('.');
        if (dotPos >= 0) {
           s = temp.substring(dotPos);

    Open in new window

    Now you know why i like it better with regex ;)
    LVL 86

    Expert Comment


    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    maxMirror challenge 10 68
    Fix45 challenge 15 66
    Performance issue while iterating with streams 5 34
    word0 challenge 3 30
    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now