Searching strings:

  • indexOf( ) Searches for the first occurrence of a character or substring.
  • lastIndexOf( ) Searches for the last occurrence of a character or substring.

  • Here, startIndex specifies the index at which point the search begins.

  • For indexOf( ), the
    search runs from startIndex to the end of the string.

  • For lastIndexOf( ), the search runs
    from startIndex to zero.

  • Here the following program:

// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));
}
}

Output:

  • Now is the time for all good men to come to the aid of their country.

indexOf(t) = 7

lastIndexOf(t) = 65

indexOf(the) = 7

lastIndexOf(the) = 55

indexOf(t, 10) = 11

lastIndexOf(t, 60) = 55

indexOf(the, 10) = 44

lastIndexOf(the, 60) = 55

Modifying a string:

Whenever you want to modify a string you want to add Stringbuffer and StringBuilder

Substring:

  • You can extract a substring using substring( ). It has two forms. The first is

                      String substring(int startIndex)
    
  • Here, startIndex specifies the index at which the substring will begin.

  • This form returns a
    copy of the substring that begins at startIndex and runs to the end of the invoking string.

  • The second form of substring( ) allows you to specify both the beginning and ending
    index of the substring:

                     String substring(int startIndex, int endIndex)
    

concat( ):

  • You can concatenate two strings using concat( ), shown here:

                      String concat(String str)
    
  • This method creates a new object that contains the invoking string with the contents of

  • str appended to the end. concat( ) performs the same function as +.

  • For example:

String s1 = "one";
String s2 = s1.concat("two");
puts the string "onetwo" into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";

replace( ):

  • The replace( ) method has two forms.
  • The first replaces all occurrences of one character in the invoking string with another character.
  • It has the following general form:

             String replace(char original, char replacement)
    
  • Here, original specifies the character to be replaced by the character specified by replacement.

       String s = "Hello".replace('l', 'w');
    
  • puts the string "Hewwo" into s.

The second form of replace( ) replaces one character sequence with another. It has this
general form:

         replace(CharSequence original, CharSequence replacement)

trim( ):

  • The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed.

  • It has this general form:

String trim( )
  • Here is an example:

    String s = " Hello World ".trim();

  • This puts the string "Hello World" into s.

  • The trim( ) method is quite useful when you process user commands.

  • These following programs are,

// Using trim() to process commands.

import java.io.*;

class UseTrim {

public static void main(String args[])

throws IOException

{

// create a BufferedReader using System.in

BufferedReader br = new

BufferedReader(new InputStreamReader(System.in));

String str;

System.out.println("Enter 'stop' to quit.");

System.out.println("Enter State: ");

do {

str = br.readLine();

str = str.trim(); // remove whitespace

if(str.equals("Illinois"))

System.out.println("Capital is Springfield.");

else if(str.equals("Missouri"))

System.out.println("Capital is Jefferson City.");

else if(str.equals("California"))

System.out.println("Capital is Sacramento.");

else if(str.equals("Washington"))

System.out.println("Capital is Olympia.");

// ...

} while(!str.equals("stop"));

}

}

Data Conversion Using valueOf( ):

  • The valueOf( ) method converts data from its internal format into a human-readable form.

  • It is a static method that is overloaded within String for all of Java’s built-in types so that each type can be converted properly into a string.

static String valueOf(double num)

static String valueOf(char chars[])

  • The valueOf( ) is called when a string representation of some other type of data is needed.

    static String valueOf

    (char chars[ ], int startIndex, int numChars)

  • chars is the array that holds the characters, startIndex is the index into the array of characters at which the desired substring begins
    and numChars specifies the length of the substring.

Changing the case of characters within the string:

  • In these methods String toUpperCase() converts all characters from string to uppercase.

  • In these methods String toLowerCase() converts all characters from string to lowercase.

In these below examples are,

// Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {

public static void main(String args[])

{

String s = "This is a test.";

System.out.println("Original: " + s);

String upper = s.toUpperCase();

String lower = s.toLowerCase();

System.out.println("Uppercase: " + upper);

System.out.println("Lowercase: " + lower);

}

}

Joining Strings:

  • JDK8 adds a new method to string is called Join().
  • It is used to concatenate the two strings by using delimiter, such as space or comma.
  • It general form is,

    static stringJoin (CharSequence delim,CharSequences..strs)

  • Here delim specify the delimiter used to separate the characters sequence specified by str.

  • Because the string implements the character sequence interfaces and str can be the list of strings.

Joining Strings:

  • Jdk8 adds a new method is called join().It used to concatenate two or more strings seperating with delimiter.(space,comma)

  • Its general form as

static String join(CharSequence delim, CharSequence . . . strs)

  • Its following program as,

// Demonstrate the join() method defined by String.

class StringJoinDemo {

public static void main(String args[]) {

String result = String.join(" ", "Alpha", "Beta", "Gamma");

System.out.println(result);

result = String.join(", ", "John", "ID#: 569",

"E-mail: [email protected]");

System.out.println(result);

}

}

  • The second form of join( ) lets you join a list of strings obtained from an object that implements the Iterable interface.

Method Description

int codePointAt(int i) Returns the Unicode code point at the location specified by i.

int codePointBefore(int i) Returns the Unicode code point at the location that precedes that specified by i.

int codePointCount(int start, int end) Returns the number of code points in the portion of the invoking String that are between start and end–1.

boolean contains(CharSequence str) Returns true if the invoking object contains the string specified by str. Returns false otherwise.

boolean contentEquals(CharSequence str) Returns true if the invoking string contains the same string as str. Otherwise, returns false.

boolean contentEquals(StringBuffer str) Returns true if the invoking string contains the same string as str. Otherwise, returns false.


StringBuffer:

  • StringBuffer supports a modifiable string.

  • As the string refers to fixed length and immutuable character sequences

  • And string buffer represents the growable and writtable sequences

  • Stringbuffer may have characters and substrings that inserted in the middle or appended end.

StringBuffer Constructors

StringBuffer defines these four constructors:

StringBuffer( )

StringBuffer(int size)

StringBuffer(String str)

StringBuffer(CharSequence chars)

  • StringBuffer allocates room for 16 additional characters when no specificbuffer length is requested.

because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory.

  • By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.

Length() and capacity();

  • The current length of the stringbuffer can be found via length method() and current capacity of the stringbuffer can be found in capacity method()

Examples:

// StringBuffer length vs. capacity.

class StringBufferDemo {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

System.out.println("buffer = " + sb);

System.out.println("length = " + sb.length());

System.out.println("capacity = " + sb.capacity());

}

}

  • Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:

buffer = Hello

length = 5

capacity = 21

  • Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.

Ensure caqqpacity():

  • It is useful when the stringbuufer is allocated the capacity.then ensure capacity is used to change the size of the buffer.

General form

void ensureCapacity(int minCapacity)

  • In these minicapacity specify the minimum size of the buffer.

  • If its size is larger than minicapacity then there is reason of efficiency.

setLength( ):

  • To set the length of the string within a StringBuffer object, use setLength( ). Its general form is shown here:

void setLength(int len)

  • Then len specifies the length of the string.

  • When you increase the size of the string, null characters are added to the end. If you call setLength( ) with a value less than the current value returned by length( ),

  • Then the new characters which is stored beyond the new length is lost.

charAt( ) and setCharAt( ):

  • The value of a single character can be obtained from a StringBuffer via the charAt( ) method.

  • You can set the value of a character within a StringBuffer using setCharAt( ).

  • Their general forms are shown here:

char charAt(int where)

void setCharAt(int where, char ch)

For charAt( ), where specifies the index of characters being obtained.

For SetCharAt() ehere specify the index of characters being set

ch specify the new value being set.

Getchars():

The general form is,

void getchars(int sourcestart, int sourceend ,char target[],int targetstart)

  • sourceStart specifies the index of the beginning of the substring, and sourceEnd

  • specifies an index that is one past the end of the desired substring.

  • This means that the substring contains the characters from sourceStart through sourceEnd–1.

  • The array that will receive the characters is specified by target.

  • The index within the target that are copied is called targetstart.

Append():

  • The append means specify the concatenation the string representation with another data type to the end of invoking string object.

  • The string representation of each parameter is obtained, often by calling String.valueOf( ).

  • The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ).

  • The general form are

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obj)

Examples:

// Demonstrate append().

class appendDemo {

public static void main(String args[]) {

String s;

int a = 42;

StringBuffer sb = new StringBuffer(40);

s = sb.append("a = ").append(a).append("!").toString();

System.out.println(s);

}

}

The output of this example is shown here:

a = 42!


Insert():

  • The insert() method insert one string into another.it is overloaded to accept all values as primitive types,charsequence,Strings,Objects

  • And then like append() it follow the string representation of data at the end of invoking Stringbuffer object.

\(same general form as like apend\(\)\)

here the index specify the starting point of string at the invoking stringbuffer object.


Reverse( ):

You can reverse the characters within a StringBuffer object using reverse( ), shown here:

       StringBuffer reverse\( \)

This method returns the reverse of the object on which it was called. The following program demonstrates reverse( ):

// Using reverse() to reverse a StringBuffer.

class ReverseDemo {

public static void main(String args[]) {

StringBuffer s = new StringBuffer("abcdef");

System.out.println(s);

s.reverse();

System.out.println(s);

}

}

Here is the output produced by the program:

abcdef

fedcba

Delete() and DeleteCharAt():

You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).

These methods are shown here:

StringBuffer delete(int startIndex, int endIndex)

The delete( ) method deletes a sequence of characters from the invoking object.

Here startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove.

Thus, the substring deleted runs from startIndex to endIndex–1.

The resulting StringBuffer object is returned.

Additional StringBuffer Methods:

Method Description

StringBuffer appendCodePoint(int ch) Appends a Unicode code point to the end of the invoking object. A reference to the object is returned.

int codePointAt(int i) Returns the Unicode code point at the location specifiedby i.

int codePointBefore(int i) Returns the Unicode code point at the location that precedes that specified by i.

int codePointCount(int start, int end) Returns the number of code points in the portion of the invoking String that are between start and end–1.

int indexOf(String str) Searches the invoking StringBuffer for the first occurrence of str. Returns the index of the match, or –1 if no match is found.

String Builder:

  • String builder is the addiotional feature added to the Java handling capabilities at JDK5.

  • The String builder is same as feature of string buffer .The only difference is it is not synced so it is thread safe.

  • The advantage of String Builder is faster performance.

results matching ""

    No results matching ""