简体   繁体   中英

Extracting substring in java that ends before a certain string

Example String: "Bobby is a cool person // not really"

I am reading from a file, and let's say I encounter the string above. I am trying to get a substring that ends just before the "//", which would yield: "Bobby is a cool person ", (please note that in my post I intentionally put two spaces after 'person', but the editor isn't picking it up - sorry) so that I can handle it easier later. Is there any way I can combine substring method with some sort of find method in java? I am reading from files and I don't know which position the "//" might show up. Do I just have to first find the position then use substring again using that position I found with indexof? Because that would be O( n^2) which isn't ideal;

I would have to agree with @achAmhain here. His solution posted is the simplest form for your problem. Of course, it can become more complicated when you start to add more condition s, or if you are attempting to parse an entire thread / document.

I would have to disagree with the last statement about time complexity,

Some one posted a question about this, which turns out to be O ( n ) found here java indexof(String str) method complexity

Now this also depends on how you designed it too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM