Reputation: 372
I need to take a String that has the following data for example: hello (world)
. My plan is, I will have the program add individual letters to another string, and test that second string and see if it has (. Then, if it does, it will start adding the letters to a third string until it finds ). That is my idea about how to get whatever is in the parentheses over to the other String. The problem is, I have no idea how to do it. I'm still kind of new to Java, and I don't know a lot of the more advanced things you can do with Strings. So if anyone has any ideas, or a tutorial explaining some code that would help me, it would be greatly appreciated.
Upvotes: 0
Views: 2313
Reputation: 15418
Make use of String.indexOf(int ch, int fromIndex)
and String.substring(int beginIndex, int endIndex)
function.
read the first index using int i = string.indexOf("(")
and then using this index to find the )
parenthesis:
int i = string.indexOf("(");
int j = string.indexof(")", i+1);
String target = string.substring(i+1, j);
Upvotes: 0
Reputation: 2212
Might want to use regex:
String myString = "Hello (world)";
Pattern pattern = Pattern.compile("\\((.*)\\)");
Matcher matcher = pattern.matcher(myString);
if (matcher.find()) {
String newString = matcher.group(1);
System.out.println(newString);
}
This will print "world".
You can get many example on Internet on how to use Regex in Java: http://www.tutorialspoint.com/java/java_regular_expressions.htm
Upvotes: 0
Reputation: 3984
You can find documentation on the String class here. That should be enough to help you figure out what is available, but if you want some helper methods, consider adding using Apache Common Lang StringUtils.
Upvotes: 0
Reputation: 1177
String.indexOf("(");
Would return the index of the first occurence of a (
.
If the data you have are always looking like that, you can then use substring() to recieve the wanted string, since the data ends with )
.
String s = "hello (world)";
String wanted = s.substring(s.indexOf("("), s.length);
should to the trick.
Upvotes: 0
Reputation: 99
This can be done using the indexOf()
and substring()
methods in the String class.
String s = "Hello (world)";
String s2 = s.substring(s.indexOf('(')+1, s.indexOf(')'));
The value of s2
should now be world
.
Upvotes: 2