How to Manipulate Strings in Java

Method 1 of 5:

Create a String

  1. How to Manipulate Strings in Java Picture 1
    Create a string using the constructor of the String class.
    String str = new String("Hello!"); 
  2. How to Manipulate Strings in Java Picture 2
    Create a string by directly assigning a string.
  3. How to Manipulate Strings in Java Picture 3
    Try an example. Here is a sample program that creates a string in two different ways.
    public class StringManipulation { public static void main(String[] args) { String str1 = new String("String created with a constructor!"); String str2 = "String created without a constructor!"; System.out.println(str1); System.out.println(str2); } } 
Method 2 of 5:

Find the Length of a String

  1. Understand what it means to find 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 6 characters.
  2. How to Manipulate Strings in Java Picture 4
    Invoke the length() method on the String object and store the result in an integer variable.
    int strLength = str.length(); 
  3. How to Manipulate Strings in Java Picture 5
    Give it a go. Here is a sample program 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 + "."); } } 
Method 3 of 5:

Reverse a String

  1. How to Manipulate Strings in Java Picture 6
    Understand what it means to reverse a string. Reversing a string means to switch the ordering of the characters in a string. For example, the reverse of the string "Hello!" is "!olleH". There are many ways to reverse a string in Java.
  2. How to Manipulate Strings in Java Picture 7
    Use the reverse method of the StringBuffer class. Create a StringBuffer object that takes in the string that you want to reverse as a parameter. Use the StringBuffer's reverse() method and then retrieve the newly reversed string by using the toString() method.
    public class StringManipulation { public static void main(String[] args) { String str = "Hello!"; StringBuffer buffer = new StringBuffer(str); String reversedStr = buffer.reverse().toString(); System.out.println("The reverse of the string "" + str + "" is "" + reversedStr + ""."); } } 
  3. How to Manipulate Strings in Java Picture 8
    Iterate through the characters in a string in reverse, appending these characters to a StringBuffer at each iteration. Create a new StringBuffer object initialized with the length of the string that you wish to reverse as the parameter. Then use a for loop to iterate through the string, starting from the last character in the string and ending at the first character in the string. At each iteration, append the character at that index to the StringBuffer. Retrieve the newly reversed string by using the toString() method.
    public class StringManipulation { public static void main(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. How to Manipulate Strings in Java Picture 9
    Write a recursive function to reverse the string. 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 string minus the first character, and the first character is tacked on at the end. So if we passed in the string "Hello!", the first reverse() call after that will have the parameter "ello!".
    public class StringManipulation { public static void main(String[] args) { String str = "Hello!"; String reversedStr = reverse(str); System.out.println("The reverse of the string "" + str + "" is "" + reversedStr + ""."); } private static String reverse(String str) { if (str == null || str.length() <= 1) return str; return reverse(str.substring(1)) + str.charAt(0); } } 
  5. How to Manipulate Strings in Java Picture 10
    Convert the string to an array of characters and then swap the first and last, second and second to last, etc. characters. First convert the string to an array of characters by using the toCharArray() method on the string. Get the index of the last character in the array, which is equal to the length of the array minus one. Then iterate through the array, swapping the ith character and the indexOfLastChar - ith character at each iteration. Finally, convert the character array back to a string.
    public class StringManipulation { public static void main(String[] args) { String str = "Hello!"; 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. How to Manipulate Strings in Java Picture 11
    Review your output. Here is the output that results from any one of these methods for string reversal.
Method 4 of 5:

Trim White Space in a String

  1. How to Manipulate Strings in Java Picture 12
    Understand what it means to trim white space in a string. Trimming a string in Java means to remove the leading and trailing white space in the string. For example, if you have the string "
     
    Hello, world!
     
    " and you want to have it say "Hello, world!" without the white space in the beginning and in the end, you can trim the string. The String class provides a method to trim() which returns a copy of the string with leading and trailing white space removed or the original string if it has no leading or trailing white space.
  2. How to Manipulate Strings in Java Picture 13
    Use the trim() method of the String class on a String object to trim the white space. Note that the trim() method will throw an exception if the string is null. The trim() method will not change the contents of the original string because strings in Java are immutable, which means that a string's state cannot be modified after it is created. Rather, the trim() method will return a new string that has its whitespace trimmed off.
    String trimmedStr = str.trim(); 
  3. Try an example. Here is a sample program that trims the white space of a string:
    public class StringManipulation { public static void main(String[] args) { String str = " Hello! "; String trimmedStr = str.trim(); System.out.println("Original String is "" + str + ""."); System.out.println("Trimmed String is "" + trimmedStr + ""."); } } 
Method 5 of 5:

Split a String

  1. How to Manipulate Strings in Java Picture 14
    Understand what it means to split a string. Splitting a string in Java means to split a string by a certain delimiter into an array of substrings. For example, if I split the string "red,blue,green,yellow,pink" with a comma as the delimiter, I would get the array { "red", "blue", "green", "yellow", "pink" }. Here are three different ways to split a string.
  2. How to Manipulate Strings in Java Picture 15
    Use StringTokenizer to tokenize the string. Import java.util.StringTokenizer. Then create a new instance of a StringTokenizer with the string to tokenize and the delimiter as parameters. If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space. After you have the StringTokenizer, you can use the nextToken() method to get each token.
    import java.util.Arrays; import java.util.StringTokenizer; public class StringManipulation { public static void main(String[] args) { String str = "red,green,blue,yellow,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); System.out.println("Split Array: " + Arrays.toString(splitArr) + "n"); } } 
    1. Before Java 1.4, the StringTokenizer class was used to split strings in Java. But now, the use of StringTokenizer is discouraged and the use of the split() method in the String class or the use of the java.util.regex package is encouraged.
  3. How to Manipulate Strings in Java Picture 16
    Use the String class's split() method. The split() method will take in the delimiter as a param and return an array of sub-strings that are the same as the tokens from the StringTokenizer.
    import java.util.Arrays; public class StringManipulation { public static void main(String[] args) { String str = "red,green,blue,yellow,pink"; String[] splitArr = str.split(","); System.out.println("nOriginal String: " + str); System.out.println("Split Array: " + Arrays.toString(splitArr) + "n"); } } 
  4. How to Manipulate Strings in Java Picture 17
    Use regular expressions to split the string. Import java.util.regex.Pattern. Use the compile() method of the Pattern class to set the delimiter and then give the split() method the string that you want to split. The Pattern will return an array of substrings.
    import java.util.Arrays; import java.util.regex.Pattern; public class StringManipulation { public static void main(String[] args) { String str = "red,green,blue,yellow,pink"; String[] splitArr = Pattern.compile(",").split(str); System.out.println("nOriginal String: " + str); System.out.println("Split Array: " + Arrays.toString(splitArr) + "n"); } } 
  5. How to Manipulate Strings in Java Picture 18
    Review your output. Here is the output that results from any one of these methods for splitting strings.
5 ★ | 1 Vote

May be interested

  • How to fix the error does not install JavaHow to fix the error does not install Java
    more and more applications and websites require java installation before use. unfortunately, sometimes you can't install java or install it, but it doesn't work. the article will provide ways to fix errors that do not install java on your computer.
  • How to Tune a Java Virtual Machine (JVM)How to Tune a Java Virtual Machine (JVM)
    the java virtual machine (jvm) runs your java programs. sometimes the default configuration that the jvm comes with may not be the most efficient for your program.
  • What is the difference between Go and Java?What is the difference between Go and Java?
    is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
  • How to Fix JavaHow to Fix Java
    java is a computing platform that allows you to play games and view videos on your computer. you can tell that your computer is having problems with java if you see java errors appear when you try to run a program or visit a website that...
  • How to Compile a Java ProgramHow to Compile a Java Program
    this wikihow teaches you how to turn your java source code into an executable app using a local and online compiler. if you're using a computer, the most common way to compile java code is using java software development kit (java sdk)...
  • Oracle wants to turn Java EE into fully open sourceOracle wants to turn Java EE into fully open source
    this week, oracle announced plans to move java ee project management to an open source platform, like apache or eclipse.
  • Write and run Java code on the computer for the first timeWrite and run Java code on the computer for the first time
    after you've installed java and set up a path on your computer, you need to know how to run a simple java code on your computer. in this article, we will try to write the first java program, as well as the commands to run this program in cmd.
  • Download Java Runtime Environment 8-build-251Download Java Runtime Environment 8-build-251
    java runtime environment (jre) is a software class that provides the services needed to execute java applications. it is an essential component of the java development kit (jdk) and contains all the tools needed to run various java-based software programs.
  • How to Enable JavaHow to Enable Java
    java is a programming language and platform commonly used in a number of websites and applications. when java is not enabled, you can experience difficulty with viewing or using certain websites and applications. to use java, you must have...
  • 200 common Java interview questions, with reference answers200 common Java interview questions, with reference answers
    if you are going to a java interview, preparing for java programming language questions is necessary. these java interview questions are compiled from tutorialspoint and are accompanied by reference answers.