How to return everything after x characters in a string
Say I had String s = "This开发者_运维知识库 is a loooooooooooooooong string";
. Now say I want to cut off This
and return everything else. How would I do this? What I'm asking is, is there a method that returns everything after x
characters?
Yes there is. And that method is the substring()
method, which takes an integer as its argument and slices off everything before the specified character position.
String s = "This is a loooooooooooooooong string";
System.out.println(s.substring(5));
Output:
is a loooooooooooooooong string
You are looking for string result = s.substring(4);
String#substring(int)
takes the start index.
Sure. :-)
return s.substring(5);
substring
is what you're looking for.
Example from the docs:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
You'll want to use String.substring(int)
. It takes a String
and returns a piece of it. Like most things in Java, it is zero-based. That means that the first character is 0, not 1. Also, substring
is inclusive. That means it will keep the character indicated by the index, not lose it. Finally, substring
does not change the original string, so you need to assign the return value to something. Here's an example:
String str = "Hello World!";
System.out.println(str.substring(6)); // World!
System.out.println(str); // Hello World!
Now, sometimes you want to take a part of the string that is in the beginning or middle, not the end. You can do this with String.substring(int, int)
. This has two ints, the start index and the end index. Now, while the start index is inclusive, the end index is exclusive. Here's an example:
String str = "Hello World!";
System.out.println(str.substring(0, 5)); // Hello
You can find both of these methods in the JavaDocs. In fact, generally the first Google result for the phrase java {class name}
is the reference for that class, so they're easy to look up. They're extremely useful, so be sure to check them out.
substring() is the method you can use.
String word= "This";
return s.substring(word.length());
精彩评论