Java Read Only First 10 Character of String

The Cord grade 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

Y'all can get the character at a particular index within a string by invoking the charAt() accessor method. The alphabetize of the first graphic symbol is 0, while the index of the last graphic symbol is length()-i. For instance, the post-obit code gets the character at index 9 in a string:

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

Indices brainstorm at 0, so the character at index ix is 'O', as illustrated in the following figure:

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

If you lot want to get more than than one sequent character from a string, you tin apply the substring method. The substring method has two versions, as shown in the post-obit tabular array:

The substring Methods in the String Class
Method Description
Cord 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 graphic symbol at index endIndex - 1.
String substring(int beginIndex) Returns a new string that is a substring of this cord. The integer argument specifies the index of the first grapheme. Here, the returned substring extends to the end of the original string.

The following lawmaking gets from the Niagara palindrome the substring that extends from index 11 upwardly to, but not including, alphabetize 15, which is the give-and-take "roar":

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

Other Methods for Manipulating Strings

Hither are several other String methods for manipulating strings:

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

Searching for Characters and Substrings in a String

Hither are some other Cord methods for finding characters or substrings within a string. The String grade provides accessor methods that render the position within the cord of a specific grapheme or substring: indexOf() and lastIndexOf(). The indexOf() methods search forward from the starting time of the cord, and the lastIndexOf() methods search backward from the end of the string. If a character or substring is not found, indexOf() and lastIndexOf() return -i.

The Cord class besides provides a search method, contains, that returns true if the string contains a particular graphic symbol sequence. Use this method when you but need to know that the string contains a character sequence, merely the precise location isn't important.

The post-obit table describes the various string search methods.

The Search Methods in the String Class
Method Description
int indexOf(int ch)
int lastIndexOf(int ch)
Returns the index of the first (terminal) occurrence of the specified grapheme.
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
Returns the index of the start (final) occurrence of the specified graphic symbol, searching forward (backward) from the specified index.
int indexOf(String str)
int lastIndexOf(String str)
Returns the alphabetize of the beginning (last) occurrence of the specified substring.
int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index.
boolean contains(CharSequence s) Returns truthful if the cord contains the specified character sequence.

Note:CharSequence is an interface that is implemented by the String course. Therefore, you can use a cord 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 general, they are not needed: You can create a new string by chain of substrings you accept removed from a string with the substring that you want to insert.

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

Methods in the String Class for Manipulating Strings
Method Description
Cord replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this cord with newChar.
String supplant(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.
String replaceFirst(String regex, String replacement) Replaces the beginning substring of this string that matches the given regular expression with the given replacement.

An Instance

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


Notation: The methods in the post-obit Filename class don't do any error checking and assume that their argument contains a full directory path and a filename with an extension. If these methods were product lawmaking, they would verify that their arguments were properly constructed.


              public class Filename {     private String fullPath;     individual char pathSeparator,                   extensionSeparator;      public Filename(String 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 String filename() {         int dot = fullPath.lastIndexOf(extensionSeparator);         int sep = fullPath.lastIndexOf(pathSeparator);         render fullPath.substring(sep + 1, dot);     }      public Cord path() {         int sep = fullPath.lastIndexOf(pathSeparator);         return fullPath.substring(0, sep);     } }          

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

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

And here's the output from the programme:

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

As shown in the following figure, our extension method uses lastIndexOf to locate the concluding occurrence of the period (.) in the file proper name. Then substring uses the render value of lastIndexOf to extract the file proper noun extension — that is, the substring from the catamenia to the end of the string. This code assumes that the file name has a period in it; if the file proper name does not take a catamenia, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

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

Also, find that the extension method uses dot + 1 as the argument to substring. If the menstruation character (.) is the last graphic symbol of the cord, dot + i is equal to the length of the string, which is i larger than the largest index into the string (considering indices start at 0). This is a legal argument to substring considering that method accepts an index equal to, simply not greater than, the length of the string and interprets it to hateful "the finish of the string."

kunzeounins.blogspot.com

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

0 Response to "Java Read Only First 10 Character of String"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel