Common methods of handling strings in Java programming _java

Source: Internet
Author: User
Tags instance method locale lowercase uppercase letter stringbuffer

Character
Typically, when we process characters, we use the raw data type char.

Example

char ch = ' a ';

Unicode for uppercase Greek Omega character
char Unichar = ' \u039a '; 

An array of chars
char[] chararray ={' A ', ' B ', ' C ', ' d ', ' e '};

In development, however, we encounter situations where objects need to be used rather than the original data type. In order to achieve this demand. Java provides wrapper class Character for raw data type char.

The Character class provides a series of useful classes for manipulating characters (for example, static classes). You can create a Character object with the help of the Character constructor.

Character ch = new Character (' a ');

The Java compiler will also be able to create a Character object for you in some situations. For example, if you transfer an original char to a method of an object that can be expected, the compiler will automatically convert char to Character. If the conversion is in the opposite direction, this feature is called automatic boxing or unboxing.

Example

Here following primitive char ' a '
//are boxed into the Character object ch
Character ch = ' a ';

Here primitive ' x ' are boxed for method test,
//Return is unboxed to char ' C '

char c = Test (' x ');

Escape sequence
the character preceded by a backslash (\) is an escape sequence and has special meaning for the compiler.

The newline character (\ n) is used frequently in System.out.println () statements, and the string wraps when it is printed.

The following table shows the Java escape sequence:

Escape sequence Description
\ t Inserts a label into the text.
\b Inserts a backspace in the text.
\ n Inserts a newline character into the text.
\ r Inserts a carriage return in the text.
\f Inserts a page change into the text.
\' Inserts a single quote character into the text.
\\ Inserts a backslash character in the text.

When an escape sequence encounters a print statement, the compiler will interpret it accordingly.

Example

If you want to enclose quotes in quotes, you must use the escape sequence, \, to quote internally:

public class Test {public

 static void Main (String args[]) {
  System.out.println (' She said \ hello!\ ' to me. ');
 }
}

This will produce the following results:

She said "hello!" to me.
Character method
The following list is an important instance method for implementing all subclasses of the Character class:

SN Method Description
1 Isletter ()
Determines that the specific char value is a letter
2 IsDigit ()
Determines that the specific char value is a number
3 Iswhitespace ()
Determines that the specific char value is a space
4 Isuppercase ()
Determines that the specific char value is an uppercase letter
5 Islowercase ()
Determines that the specific char value is a lowercase letter
6 toUpperCase ()
Returns the uppercase form of the specified character value
7 toLowerCase ()
Returns the lowercase write form of the specified character value
8 ToString ()
Returns a String object that represents the specified character value, that is, a character literal


string
string, which is widely used in Java programming, is a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides a string class to create and manipulate strings.

Creating a String
the most straightforward way to create a string is to write this:

String greeting = "Hello world!";
When you create a string, the compiler creates a string object with its value in this case, such as: "Hello world!".

Any other object can create a String object through the use of the new keyword and through the constructor. The string class has 11 constructors that provide initial values that use different types of strings, such as an array of characters.

public class stringdemo{public

 static void Main (String args[]) {
  char[] Helloarray = {' h ', ' e ', ' l ', ' l ', ' o ', '. '};
  String hellostring = new string (helloarray); 
  System.out.println (hellostring);
 }


This will produce the following results:

Hello.

Note the string class is immutable, so once you create a string object, you cannot change it. If you need a large number of characters to modify the string, then you should use the StringBuffer & StringBuilder class.

String length
the method used to get information about the object is called the access method. One access method that can be used with a string is length (), which returns the number of characters contained in a string object.

After the following two lines of code are executed, Len equals 17:

public class Stringdemo {public

 static void main (string args[]) {
  string palindrome = ' Dot saw I was Tod ';
  int len = Palindrome.length ();
  System.out.println ("String Length is:" + len);
 }


This will produce the following results:

String Length is:17

Connection string
the String class includes methods for connecting two strings:

String1.concat (string2);

This returns a new string that adds string2 at the end of the string1. You can also use the concat () method to connect strings, such as:

"My name is". Concat ("Zara");

Strings are more commonly connected by using the "+" operator, such as:

"Hello," + "world" + "!"

This will produce:

"Hello, world!."

Take a look at the following example:

public class Stringdemo {public

 static void main (string args[]) {
  string string1 = ' saw I was ';
  System.out.println ("Dot" + string1 + "Tod");
 }


This will produce the following results:

Dot saw I was Tod

Create a formatted string
you already have the printf () and format () methods to print numbers in the output format. The string class has an equivalent method format () that returns a String object instead of a PrintStream object.

Using the static format () method of a string allows you to create a reusable formatted string instead of a one-time print statement. For example, if you replace the following methods:

System.out.printf ("The value of the float variable is" +
     "%f, while the value of the" +
     "variable is% D, and the string "+
     is%s", Floatvar, Intvar, stringvar);

You can write this:

String FS;
FS = String.Format ("The value of the float variable is" +
     "%f) while the ' value of ' is ' +
     ' variable is%d , and the string "+ is
     %s", Floatvar, Intvar, stringvar);
SYSTEM.OUT.PRINTLN (FS);

String method
here is a list of methods supported by the String class:

SN Method and Description
1 char charAt (int index)
Returns the character at the specified index.
2 int CompareTo (Object o)
Compare this string to another object.
3 int CompareTo (String anotherstring)
Compares the dictionary order of two strings.
4 int comparetoignorecase (String str)
Compares two strings in dictionary order, case-insensitive differences.
5 String concat (String str)
Concatenates the specified string to the end of this string.
6 Boolean contentequals (StringBuffer SB)
Returns true if and only if the string represents the same character sequence as the specified stringbuffer.
7 Static String copyvalueof (char[] data)
Returns a string representing the sequence of characters in the specified array.
8 Static String copyvalueof (char[] data, int offset, int count)
Returns a string representing the sequence of characters in the specified array.
9 Boolean endsWith (String suffix)
Tests whether this string ends with the specified suffix.
10 Boolean equals (Object anobject)
Compares this string with the specified object.
11 Boolean equalsignorecase (String anotherstring)
Compare this string to another string, ignoring case considerations.
12 Byte GetBytes ()
Decodes this string to use the platform's default character set and stores the result in a sequence of bytes in a new byte array.
13 Byte[] GetBytes (String charsetname
Decodes this string using the byte sequence of the specified character set and stores the result in a new byte array.
14 void GetChars (int srcbegin, int srcend, char[] DST, int dstbegin)
Copies characters from this string to the destination character array.
15 int Hashcode ()
Returns a hash code for this string.
16 int indexOf (int ch)
Returns the index at which this string specifies the first occurrence of the character.
17 int indexOf (int ch, int fromindex)
Returns the first occurrence of the specified character in this string, starting the search at the specified index.
18 int indexOf (String str)
Returns the index at the first occurrence of this string specifying the substring.
19 int indexOf (String str,int fromindex)
Returns the index at the first occurrence of the specified substring in this string, starting at the specified index.
20 String Intern ()
Returns the normalized representation of a string object.
21st int lastindexof (int ch)
Returns the index at which this string specifies the last occurrence of the character.
22 int lastindexof (int ch, int fromindex)
Returns the index at which this string specifies the last occurrence of the character, searching backwards from the specified index.
23 int LastIndexOf (String str)
Returns the index at the rightmost occurrence of this string specifying a substring.
24 int LastIndexOf (String str, int fromindex)
Returns the last occurrence of the specified substring in this string, which is searched backwards from the beginning of the specified index.
25 int Length ()
Returns the length of this string.
26 Boolean matches (String regex)
Determines whether this string matches a given regular expression.
27 Boolean Regionmatches (boolean ignoreCase, int toffset, String other, int ooffset, int len)
The range that tests two strings is equal to.
28 Boolean regionmatches (int toffset, String other, int ooffset, int len)
The regions that test two strings are equal.
29 String replace (char Oldchar, char Newchar)
Returns from the Newchar replacement Oldchar all occurrences in this string produce a new string.
30 String ReplaceAll (string regex, string replacement
Replaces each substring of a given regular expression in this string that matches a given replacement.
31 String Replacefirst (string regex, string replacement)
Replace this string to match the given regular expression given the substitution of the first substring.
32 String[] Split (String regex)
Splits this string around the given regular expression.
33 String[] Split (String regex, int limit)
Splits this string around the given regular expression.
34 Boolean startswith (String prefix)
Tests whether this string begins with the specified prefix.
35 Boolean startswith (String prefix, int toffset)
Tests whether this string starts with the specified prefix starting at the specified index.
36 Charsequence subsequence (int beginindex, int endindex)
Returns a new sequence of characters, the subsequence of this sequence.
37 String substring (int beginindex)
Returns a new string that is a substring of this string.
38 String substring (int beginindex, int endindex)
Returns a new string that is a substring of this string.
39 Char[] ToCharArray ()
This string is converted to a new character array.
40 String toLowerCase ()
Use the default locale's rule lowercase for all characters in this string.
41 String toLowerCase (Locale Locale)
Use the rule lowercase for all characters in this string using the given locale.
42 String toString ()
This object (it is already a string!) Returns the string form (this is itself).
43 String toUpperCase ()
Converts all characters in this string to uppercase using the rules for the default locale.
44 String toUpperCase (Locale Locale)
Converts all characters in this string to uppercase using the given locale rule.
45 String Trim ()
Returns a copy of the string, with the start and end spaces removed.
46 Static String valueof (primitive data type X)
Returns a string representation of the passed data type parameter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.