How to Read in Strings in Java
Download Commodity
Download Article
Strings are sequences of characters. For example, "Hello!" is a string considering it is fabricated up of the characters 'H', 'e', 'l', 'l', 'o', and '!'. In Java, strings are objects, which means that in that location is a String grade that has fields and methods. Nosotros tin can utilize the methods of the String class to manipulate strings.
-
i
Create a string using the constructor of the String course.
String str = new String ( "Hello!" );
-
ii
Create a string by directly assigning a string.
Advertising
-
3
Endeavour an case. Here is a sample program that creates a cord in two dissimilar ways.
public grade StringManipulation { public static void main ( Cord [] args ) { String str1 = new String ( "String created with a constructor!" ); Cord str2 = "String created without a constructor!" ; System . out . println ( str1 ); System . out . println ( str2 ); } }
Advertizing
-
1
Sympathize what information technology ways to notice the length of a string. The length of a string is the number of characters that the string contains. For example, the length of the string "Hello!" is 6 because it has half-dozen characters.
-
ii
Invoke the
length()
method on the String object and store the effect in an integer variable.int strLength = str . length ();
-
three
Requite it a go. Hither is a sample programme that finds the length of a string.
public class StringManipulation { public static void main ( String [] args ) { String str = "Hello!" ; int strLength = str . length (); System . out . println ( "The length of \"" + str + "\" is " + strLength + "." ); } }
Advertisement
-
1
Sympathise what it means to opposite a string. Reversing a cord means to switch the ordering of the characters in a cord. For example, the opposite of the string "Howdy!" is "!olleH". There are many ways to opposite a string in Coffee.
-
2
Use the contrary method of the StringBuffer class. Create a StringBuffer object that takes in the cord that you want to reverse every bit a parameter. Utilise the StringBuffer'south opposite() method and then retrieve the newly reversed string past using the toString() method.
public class StringManipulation { public static void principal ( Cord [] args ) { String str = "Hullo!" ; StringBuffer buffer = new StringBuffer ( str ); String reversedStr = buffer . reverse (). toString (); System . out . println ( "The reverse of the cord \"" + str + "\" is \"" + reversedStr + "\"." ); } }
-
iii
Iterate through the characters in a string in opposite, appending these characters to a StringBuffer at each iteration. Create a new StringBuffer object initialized with the length of the string that you lot wish to reverse equally the parameter. And so utilize a for loop to iterate through the string, starting from the terminal grapheme in the string and ending at the first character in the string. At each iteration, suspend the grapheme at that index to the StringBuffer. Call back the newly reversed string by using the toString() method.
public class StringManipulation { public static void principal ( String [] args ) { String str = "Hello!" ; StringBuffer buffer = new StringBuffer ( str . length ()); for ( int i = str . length () - 1 ; i >= 0 ; i --) { buffer . append ( str . charAt ( i )); } String reversedStr = buffer . toString (); System . out . println ( "The reverse of the string \"" + str + "\" is \"" + reversedStr + "\"." ); } }
-
4
Write a recursive function to contrary the cord. In the recursive function, the base case / condition is if the string is null or if the length of the string is less than or equal to none. Otherwise, the reverse() method is called again with the cord minus the start character, and the first character is tacked on at the end. So if we passed in the string "Hello!", the beginning opposite() call after that volition have the parameter "ello!".
public class StringManipulation { public static void main ( String [] args ) { String str = "Hello!" ; String reversedStr = reverse ( str ); Organization . out . println ( "The opposite of the string \"" + str + "\" is \"" + reversedStr + "\"." ); } individual static String reverse ( String str ) { if ( str == null || str . length () <= 1 ) return str ; return reverse ( str . substring ( ane )) + str . charAt ( 0 ); } }
-
5
Convert the string to an array of characters and then bandy the commencement and last, second and 2d to last, etc. characters. Get-go convert the string to an array of characters by using the toCharArray() method on the string. Go the alphabetize of the concluding grapheme in the array, which is equal to the length of the assortment minus one. Then iterate through the array, swapping the ith grapheme and the indexOfLastChar - ith grapheme at each iteration. Finally, catechumen the character array back to a string.
public class StringManipulation { public static void chief ( String [] args ) { String str = "Hi!" ; char [] charArray = str . toCharArray (); int indexOfLastChar = charArray . length - 1 ; for ( int i = 0 ; i < charArray . length / 2 ; i ++) { char temp = charArray [ i ]; charArray [ i ] = charArray [ indexOfLastChar - i ]; charArray [ indexOfLastChar - i ] = temp ; } String reversedStr = new String ( charArray ); System . out . println ( "The reverse of the string \"" + str + "\" is \"" + reversedStr + "\"." ); } }
-
6
Review your output. Here is the output that results from any ane of these methods for cord reversal.
Advertising
-
1
Understand what it ways to trim white space in a string. Trimming a string in Java means to remove the leading and trailing white space in the cord. For example, if you lot have the string "
Hello, world!
" and you lot want to take it say "Hello, earth!" without the white space in the outset and in the end, yous tin trim the string. The String class provides a method to trim() which returns a copy of the cord with leading and trailing white space removed or the original string if it has no leading or trailing white space.
-
2
Utilize the trim() method of the Cord class on a String object to trim the white space. Annotation that the trim() method will throw an exception if the cord is null. The trim() method will not change the contents of the original string because strings in Java are immutable, which ways that a cord's state cannot be modified after it is created. Rather, the trim() method will return a new string that has its whitespace trimmed off.
Cord trimmedStr = str . trim ();
-
iii
Try an example. Hither is a sample program that trims the white space of a string:
public class StringManipulation { public static void master ( String [] args ) { String str = " Hello! " ; String trimmedStr = str . trim (); Organization . out . println ( "Original Cord is \"" + str + "\"." ); System . out . println ( "Trimmed Cord is \"" + trimmedStr + "\"." ); } }
Ad
-
1
Understand what it means to split a string. Splitting a string in Java means to separate a cord past a certain delimiter into an assortment of substrings. For example, if I split the string "red,blueish,green,yellow,pink" with a comma as the delimiter, I would get the array { "red", "blue", "green", "yellow", "pinkish" }. Here are three different ways to split a string.
-
2
Use
StringTokenizer
to tokenize the cord. Importjava.util.StringTokenizer
. Then create a new instance of aStringTokenizer
with the cord to tokenize and the delimiter every bit parameters. If y'all do not enter the delimiter as a parameter, the delimiter will automatically default to white space. After y'all have theStringTokenizer
, you can apply thenextToken()
method to get each token.- Before Java 1.4, the
StringTokenizer
class was used to split strings in Coffee. Only now, the apply ofStringTokenizer
is discouraged and the utilize of thecarve up()
method in theString
form or the use of thejava.util.regex
bundle is encouraged.
import java.util.Arrays ; import coffee.util.StringTokenizer ; public grade StringManipulation { public static void main ( String [] args ) { Cord str = "carmine,green,blueish,xanthous,pink" ; StringTokenizer tokenizer = new StringTokenizer ( str , "," ); int numberOfTokens = tokenizer . countTokens (); String [] splitArr = new String [ numberOfTokens ]; for ( int i = 0 ; i < numberOfTokens ; i ++) { splitArr [ i ] = tokenizer . nextToken (); } System . out . println ( "\nOriginal String: " + str ); Organisation . out . println ( "Split Assortment: " + Arrays . toString ( splitArr ) + "\n" ); } }
- Before Java 1.4, the
-
3
Utilize the
String
class'ssplit()
method. Thesplit()
method will accept in the delimiter as a param and return an array of sub-strings that are the same equally the tokens from theStringTokenizer
.import java.util.Arrays ; public grade StringManipulation { public static void chief ( String [] args ) { String str = "ruby-red,green,blue,yellowish,pinkish" ; String [] splitArr = str . split ( "," ); System . out . println ( "\nOriginal Cord: " + str ); System . out . println ( "Separate Array: " + Arrays . toString ( splitArr ) + "\n" ); } }
-
iv
Use regular expressions to split the string. Import
java.util.regex.Pattern
. Utilize thecompile()
method of theDesign
grade to gear up the delimiter and so requite thedissever()
method the string that yous want to carve up. TheBlueprint
volition return an array of substrings.import java.util.Arrays ; import java.util.regex.Design ; public class StringManipulation { public static void main ( String [] args ) { Cord str = "red,greenish,blue,yellowish,pink" ; String [] splitArr = Design . compile ( "," ). split up ( str ); System . out . println ( "\nOriginal String: " + str ); Arrangement . out . println ( "Split Array: " + Arrays . toString ( splitArr ) + "\due north" ); } }
-
5
Review your output. Here is the output that results from any one of these methods for splitting strings.
Ad
Add New Question
-
Question
How do I get output from this program?
Yous can print to standard output in Coffee past using System.out.println(myObject);
Ask a Question
200 characters left
Include your email address to become a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
Nearly This Commodity
Thanks to all authors for creating a folio that has been read 121,987 times.
Is this commodity upwardly to date?
Source: https://www.wikihow.com/Manipulate-Strings-in-Java
0 Response to "How to Read in Strings in Java"
Publicar un comentario