Skip to main content
Published on

Methods I in Java

Share:

Introduction

In this article, we will explore two crucial methods in Java: substring() and split(). These methods are fundamental for string manipulation and have varied applications.

The substring() Method

The substring() method is used to extract a part of a string. It can be used in two ways:

  1. substring(int beginIndex): Returns a new string from the specified index to the end of the original string.
  2. substring(int beginIndex, int endIndex): Returns a new string from the start index to the end index, excluding the character at the end index.

Practical Applications

  • Extracting domain names from URLs.
  • Removing specific prefixes or suffixes from strings.
  • Obtaining unique identifiers or codes from larger strings.

The split() Method

The split() method divides a string into an array of substrings, using a regular expression as the delimiter.

Regular Expressions and the split() Method

  • The split() method accepts regular expressions (Regex), which makes it extremely powerful and versatile.
  • For example, split("\\s+") uses Regex to split the string by one or more spaces.

Practical Applications

  • Parsing and processing CSV or delimited text files.
  • Extracting words or tokens from a text for natural language processing (NLP).
  • Manipulating data in logs or formatted text files.
package com.caffeinealgorithm.programaremjava;

public class MethodsI {
  private String oneTwoThree = "OneTwoThree", name = "Nelson Gomes da Silva";

  public void Run() {
    // substring()
    System.out.printf("1: %s\n", oneTwoThree.substring(0, 2));
    System.out.printf("2: %s\n", oneTwoThree.substring(2, 6));
    System.out.printf("3: %s\n", oneTwoThree.substring(6));

    // split()
    var words = name.split(" ");

    for (String word : words)
      System.out.printf("Word: %s\n", word);

    var _words = name.split(" Gomes da ");
    System.out.printf("Name: %s %s", _words[0], _words[1]);
  }
}

/*
  1: On
  2: eTwo
  3: Three
  Word: Nelson
  Word: Gomes
  Word: da
  Word: Silva
  Name: Nelson Silva
*/

Additional Considerations

  • Performance and Optimization: Although both methods are efficient, it is important to be mindful of intensive use in loops or with very large strings, which can impact performance.
  • Exception Handling: Always validate the indices in substring() and consider possible PatternSyntaxException in split() when using complex regular expressions.

Conclusion

Understanding and knowing how to use substring() and split() is fundamental for any Java developer. These methods offer efficient ways to manipulate and process strings, an essential skill in software development.

Happy coding!