All string function in java with example

Strings

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

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, «Hello world!» is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world! .

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = < 'h', 'e', 'l', 'l', 'o', '.' >; String helloString = new String(helloArray); System.out.println(helloString);

The last line of this code snippet displays hello .

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

Читайте также:  Python open file errno 2 no such file or directory

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod"; int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i) , which returns the i th character in the string, counting from 0.

public class StringDemo < public static void main(String[] args) < String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an // array of chars for (int i = 0; i < len; i++) < tempCharArray[i] = palindrome.charAt(i); >// reverse array of chars for (int j = 0; j < len; j++) < charArray[j] = tempCharArray[len - 1 - j]; >String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); > >

Running the program produces this output:

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars() , to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0);

Concatenating Strings

The String class includes a method for concatenating two strings:

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

The + operator is widely used in print statements. For example:

String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");

Such a concatenation can be a mixture of any objects. For each object that is not a String , its toString() method is called to convert it to a String .

Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example:

String quote = "Now is the time for all good " + "men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.

Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format() , that returns a String object rather than a PrintStream object.

Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + "and the string is %s", floatVar, intVar, stringVar);
String fs; fs = String.format("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + " and the string is %s", floatVar, intVar, stringVar); System.out.println(fs);

Источник

String Functions in Java

String Functions In Java

A number of methods provided in Java to perform operations in Strings are called String functions. The methods are compare(), concat(), equals(), split(), length(), replace(), compareTo() and so on. Strings in Java are constant and created using a literal or keyword. String literal makes Java memory efficient, and the keyword creates a Java string in normal memory. The string represents an array of character values, and the class is implemented by three interfaces such as Serializable, Comparable, and CharSequence interfaces. It represents the sequence of characters in a serialized or comparable manner.

Concept of String Functions in Java

Below are the main concepts of String Functions in java:

1. Creating String

In Java, there are two primary ways to create a String object:

Using a string literal: Double quotes are used to produce a string literal in Java.

Using the new keyword: Java String can be created using “new”.

String s=new String ("Hello World!");

2. String length

Methods that are used to get information about an object are called accessor methods in Java. One such accessor method related to strings is the length () method. This returns the number of characters in the string object.

String length

3. Concatenating string

This method returns a new string which is string1 with string2 combined at the end. Concat () method can be used with string literals to get this done. Strings are also commonly concatenated using the + operator.

Concatenating string

4. Creating a format string

The printf() and format() functions output formatted numbers. The string has a similar class method named format (). It yields a String object. In contrast to the one-time print command, the static format () method accessible in the String object permits the construction of a formatted string that may be reused.

Methods of String Functions in Java

The following are the different methods:

Method Description
char charAt(int index) It returns the char value of the particular index as mentioned.
int length() It returns the length of the string
static String format(String format, Object… args) It returns a string that is duly formatted.
static String format(Locale l, String format, Object… args) It returns a formatted string along with the given locale.
String substring(int beginIndex) It returns the substring, which starts from begin index.
String substring(int beginIndex, int endIndex) It returns a substring for a given start index position and ends index.
boolean contains(CharSequence s) It returns true or false after doing a match between the sequence of char values.
static String join(CharSequence delimiter, CharSequence… elements) It returns a string that is joined
static String join(CharSequence delimiter, Iterable elements) It returns a joined string, the same as above.
boolean equals(Object another) It checks the equality of the string. It does so with the given object.
boolean isEmpty() It checks if a given string is empty or not.
String concat(String str) It concatenates the specified string like the above example.
String replace(char old, char new) It replaces all occurrences of the specified old char value. With new value.
String replace(CharSequence old, CharSequence new) It replaces all occurrences of the given specified CharSequence with the new one.
static String equalsIgnoreCase(String another) It compares with another string, but It is not case-sensitive.
String[] split(String regex) It returns a split string based on matching the regex.
String[] split(String regex, int limit) It returns a split string that matches regex and limit.
String intern() It returns a string that is interned.
int indexOf(int ch) It returns the selected char value index.
int indexOf(int ch, int fromIndex) It returns the specified char value index, which starts with a given index.
int indexOf(String substring) It returns the selected substring index.
int indexOf(String substring, int fromIndex) It returns the selected substring index, which starts with a given index.
String toLowerCase() It returns a string with all chars in lowercase.
String toLowerCase(Locale l) It returns a string in lowercase with a specified locale.
String toUpperCase() It returns a string with all chars in uppercase.
String toUpperCase(Locale l) Same as above but with a specified locale.
String trim() It removes the starting and ending whitespaces of this string.
static String valueOf(int value) It converts another data type into a string. It is called an overloaded method.

Examples of String functions in Java

In this section, we have discussed some examples of string functions in Java.

Example #1: Check if a string is empty

public class IsEmptyExercise< public static void main(String args[])< String s1=""; String s2="Hello"; System.out.println(s1.isEmpty()); // true System.out.println(s2.isEmpty()); // false >>

Источник

Оцените статью