String Manipulation and Regular Expressions

String manipulation and regular expressions are essential techniques for working with textual data in programming. In Java, you can perform various operations on strings using built-in methods, and regular expressions provide a powerful way to search, manipulate, and validate strings based on patterns.


String Manipulation

1. Concatenation

You can concatenate strings using the `+` operator or the `concat()` method.

String str1 = "Hello";
String str2 = "World";
String result = str1 + ", " + str2; // Using +
String result2 = str1.concat(", ").concat(str2); // Using concat()


2. Length

You can get the length of a string using the `length()` method.

String str = "Hello, World!";
int length = str.length(); // length is 13


3. Substring

You can extract a substring from a string using the `substring()` method.

String str = "Hello, World!";
String substring = str.substring(7); // substring is "World!"


4. Splitting

You can split a string into an array of substrings using the `split()` method.

String str = "apple,orange,banana";
String[] fruits = str.split(",");
// fruits is {"apple", "orange", "banana"}


5. Replace

You can replace characters or substrings in a string using the `replace()` method.

String str = "Hello, World!";
String replaced = str.replace("Hello", "Hi");
// replaced is "Hi, World!"


Regular Expressions

Regular expressions (regex) are patterns used to match character combinations in strings.


1. Matching

You can check if a string matches a specific pattern using the `matches()` method.

String str = "Hello, World!";
boolean matches = str.matches("Hello.*");
// matches is true


2. Searching

You can search for occurrences of a pattern within a string using `Pattern` and `Matcher` classes.

import java.util.regex.*;

String str = "The cat and the mat.";
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println("Found at index: " + matcher.start());
}
// Output: Found at index: 4


3. Splitting

You can split a string using a regex pattern.

String str = "apple,orange;banana";
String[] fruits = str.split("[,;]");
// fruits is {"apple", "orange", "banana"}


4. Replacement

You can replace parts of a string based on a pattern.

String str = "apple orange banana";
String replaced = str.replaceAll("\\s", ",");
// replaced is "apple,orange,banana"


Regular expressions offer a flexible and powerful way to manipulate strings, but they can be complex and require careful attention to syntax. Java provides comprehensive support for regular expressions through the `java.util.regex` package.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....