Java: Trim an string
Find a way to trim the last character of a StringBuilder or a String for that matter.
If you have a String called 's'
If you have a StringBuilder 'sb'
Code:
s.substring(0, s.length()-1);
Code:
sb.deleteCharAt(sb.length()-1);
Java: Sort an array
Description
The java.util.Arrays.sort(int[]) method sorts the specified array of ints into ascending numerical order.
Declaration
Following is the declaration for java.util.Arrays.sort() method
public static void sort(int[] a)
Parameters
- a -- This is the array to be sorted.
Return Value
This method does not return any value.
Example:
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
Java: substring an String
Description:
This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or upto endIndex - 1 if second argument is given.
Syntax:
Here is the syntax of this method:
public String substring(int beginIndex) or public String substring(int beginIndex, int endIndex)
Parameters:
Here is the detail of parameters:
- beginIndex -- the begin index, inclusive.
- endIndex -- the end index, exclusive.
Return Value :
- The specified substring.
Example:
import java.io.*; public class Test{ public static void main(String args[]){ String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.substring(10) ); System.out.print("Return Value :" ); System.out.println(Str.substring(10, 15) ); } }
This produces following result:
Return Value : Tutorialspoint.com Return Value : Tuto
No comments:
Post a Comment