Friday, February 27, 2009

Some important String functions

Some Important String functions

String t="Important String functions";

To get length of a String

It returns total number of characters in t which is length of string
To get a single character

char ch=t.charAt(1);

This will assign 'm' to ch
To get more than one characters

This is used to get more than one characters from the string

int start_index=4;
int end_index=10;

char buffer[]=new char[end_index-start_index];

To create an array of characters

This function can be used to create an array of all the characters present in the array

char[] test=t.toCharArray();

To Compare two Strings

String anotherstring="...anything..";

Use t.equals(anotherstring);
if equals..returns true else false

Dont use == operator as it just finds whether two objects point to same instance.

Similarly we can use compareTo(anotherstring) which returns:
 Less than zero for t less than anotherstring
 Greater than zero for t greater than anotherstring
 And Zero when both the strings are equal.

 Both equals and compareto can be used with IgnoreCase extension as:
  equalsIgnoreCase(anotherstring) and compareTo(anotherstring)....

To replace a particular charcter with another character



To find whether a string contains a pattern

Here t.contains(anotherstring) is used which returns true or false depending

on whether t contains anotherstring in it.

Also contains cannot be used using IgnoreCase as no function like containsIgnoreCase

No comments:

Post a Comment

Write Your Comments..

Share this Page:-