How to Read String Until Certain Character

The String form has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing example, and other tasks.

Getting Characters and Substrings by Index

You lot tin become the character at a particular index within a cord past invoking the charAt() accessor method. The index of the starting time character is 0, while the index of the final grapheme is length()-1. For example, the following code gets the character at index nine in a string:

String anotherPalindrome = "Niagara. O roar again!";  char aChar = anotherPalindrome.charAt(nine);          

Indices brainstorm at 0, so the graphic symbol at index 9 is 'O', as illustrated in the post-obit effigy:

Use the charAt method to get a character at a particular index.

If you want to get more than one consecutive character from a string, you can employ the substring method. The substring method has two versions, as shown in the following tabular array:

The substring Methods in the String Class
Method Description
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at alphabetize endIndex - 1.
Cord substring(int beginIndex) Returns a new string that is a substring of this cord. The integer argument specifies the alphabetize of the first character. Here, the returned substring extends to the end of the original string.

The following code gets from the Niagara palindrome the substring that extends from index eleven upwardly to, but not including, index 15, which is the word "roar":

String anotherPalindrome = "Niagara. O roar over again!";  Cord roar = anotherPalindrome.substring(11, 15);          
Use the substring method to get part of a string.

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings
Method Description
Cord[] split(Cord regex)
Cord[] separate(String regex, int limit)
Searches for a lucifer as specified past the string statement (which contains a regular expression) and splits this string into an array of strings appropriately. The optional integer argument specifies the maximum size of the returned array. Regular expressions are covered in the lesson titled "Regular Expressions."
CharSequence subSequence(int beginIndex, int endIndex) Returns a new grapheme sequence constructed from beginIndex index up until endIndex - 1.
String trim() Returns a copy of this string with leading and trailing white space removed.
String toLowerCase()
String toUpperCase()
Returns a re-create of this cord converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string.

Searching for Characters and Substrings in a Cord

Here are some other String methods for finding characters or substrings within a string. The String class provides accessor methods that render the position inside the string of a specific character or substring: indexOf() and lastIndexOf(). The indexOf() methods search forrad from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string. If a character or substring is not constitute, indexOf() and lastIndexOf() render -i.

The Cord grade also provides a search method, contains, that returns true if the string contains a detail character sequence. Use this method when you but need to know that the string contains a character sequence, but the precise location isn't important.

The following table describes the various cord search methods.

The Search Methods in the String Class
Method Description
int indexOf(int ch)
int lastIndexOf(int ch)
Returns the index of the outset (last) occurrence of the specified character.
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
Returns the index of the commencement (last) occurrence of the specified character, searching frontward (backward) from the specified alphabetize.
int indexOf(String str)
int lastIndexOf(String str)
Returns the index of the get-go (last) occurrence of the specified substring.
int indexOf(String str, int fromIndex)
int lastIndexOf(Cord str, int fromIndex)
Returns the index of the start (last) occurrence of the specified substring, searching forward (backward) from the specified index.
boolean contains(CharSequence s) Returns truthful if the string contains the specified character sequence.

Note:CharSequence is an interface that is implemented by the String class. Therefore, you can use a string as an statement for the contains() method.


Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In full general, they are non needed: Yous tin can create a new string past chain of substrings you have removed from a string with the substring that you desire to insert.

The String form does have four methods for replacing found characters or substrings, however. They are:

Methods in the String Class for Manipulating Strings
Method Description
String replace(char oldChar, char newChar) Returns a new cord resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
Cord replaceFirst(String regex, String replacement) Replaces the get-go substring of this cord that matches the given regular expression with the given replacement.

An Example

The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate unlike parts of a file proper name.


Note: The methods in the following Filename class don't do whatever error checking and presume that their argument contains a total directory path and a filename with an extension. If these methods were production code, they would verify that their arguments were properly constructed.


              public class Filename {     private String fullPath;     private char pathSeparator,                   extensionSeparator;      public Filename(Cord str, char sep, char ext) {         fullPath = str;         pathSeparator = sep;         extensionSeparator = ext;     }      public String extension() {         int dot = fullPath.lastIndexOf(extensionSeparator);         return fullPath.substring(dot + 1);     }      // gets filename without extension     public Cord filename() {         int dot = fullPath.lastIndexOf(extensionSeparator);         int sep = fullPath.lastIndexOf(pathSeparator);         return fullPath.substring(sep + i, dot);     }      public String path() {         int sep = fullPath.lastIndexOf(pathSeparator);         return fullPath.substring(0, sep);     } }          

Here is a programme, FilenameDemo, that constructs a Filename object and calls all of its methods:

              public class FilenameDemo {     public static void chief(String[] args) {         final String FPATH = "/home/user/index.html";         Filename myHomePage = new Filename(FPATH, '/', '.');         Organisation.out.println("Extension = " + myHomePage.extension());         System.out.println("Filename = " + myHomePage.filename());         Organisation.out.println("Path = " + myHomePage.path());     } }          

And here'south the output from the program:

Extension = html Filename = index Path = /home/user          

As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the flow (.) in the file name. And so substring uses the return value of lastIndexOf to extract the file name extension — that is, the substring from the period to the end of the string. This lawmaking assumes that the file name has a catamenia in it; if the file proper noun does non have a catamenia, lastIndexOf returns -ane, and the substring method throws a StringIndexOutOfBoundsException.

The use of lastIndexOf and substring in the extension method in the Filename class.

Also, notice that the extension method uses dot + one as the argument to substring. If the catamenia graphic symbol (.) is the last graphic symbol of the string, dot + i is equal to the length of the cord, which is one larger than the largest alphabetize into the string (considering indices start at 0). This is a legal argument to substring because that method accepts an index equal to, but not greater than, the length of the cord and interprets it to mean "the end of the cord."

pearceappeempa.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

0 Response to "How to Read String Until Certain Character"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel