Java Reference
In-Depth Information
String newText = text.replace(' ', '/'); // Modify the string text
The first argument of the replace() method specifies the character to be replaced, and the second
argument specifies the character that is to be substituted in its place. We have stored the result in a new
variable newText here, but you could save it back in the original String variable, text , if you wanted.
To remove whitespace from the beginning and end of a string (but not the interior) you can use the
trim() method. You could apply this to a string as follows:
String sample = " This is a string ";
String result = sample.trim();
after which the String variable result will contain the string " This is a string ". This can be
useful when you are segmenting a string into substrings and the substrings may contain leading or
trailing blanks. For example, this might arise if you were analyzing an input string that contained values
separated by one or more spaces.
Creating Character Arrays from String Objects
You can create an array of variables of type char from a String variable by using the toCharArray()
method in the class String . Because this method returns an array of type char , you only need to declare
the array variable of type char[] - you don't need to allocate the array. For example:
String text = "To be or not to be";
char[] textArray = text.toCharArray(); // Create the array from the string
The toCharArray() method will return an array containing the characters of the String variable
text , one per element, so textArray[0] will contain ' T ', textArray[1] will contain ' o ',
textArray[2] will contain ' ', and so on.
You can also extract a substring as an array of characters using the method getChars() , but in this case
you do need to create an array that is large enough to hold the characters. This enables you to reuse a single
array to store characters when you want to extract a succession of substrings, and thus saves the need to
repeatedly create new arrays. Of course, the array must be large enough to accommodate the longest
substring. The method getChars() has four parameters. In sequence, these are:
Index position of the first character to be extracted (type int )
Index position following the last character to be extracted (type int )
The name of the array to hold the characters extracted (type char[] )
The index of the array element to hold the first character (type int )
You could copy a substring from text into an array with the statements:
String text = "To be or not to be";
char[] textArray = new char[3];
text.getChars(9, 12, textArray, 0);
Search WWH ::




Custom Search