Java String Replace Example Tutorial

This String replace example in Java will show you how to replace String in Java both at character level and by using regular expression. Since String is final in Java every time you replace String you will get a new String object only if your actually replace anything on original String otherwise replacemethods of String return same String object. String Class in Java provides 4 methods to replace String in Java. Those methods allow you to replace character from String, replace CharacterSequence from String, replace all occurrence ofpattern in String or just first occurrence of any pattern in Java. We will also see important points on String replace method and how to make best use of regular expression while replace string in Java.

This article is on series of my other String article like2 ways to Split String in Java and how to convert String to Date in Java. String is one of the most important classes in Java and having a good knowledge of String class is mandatory for any Java developer.

Java String Replace Example and Tutorial in Java


Java String replace example tutorialString Replace Examples in Java

As I said earlier Java provides at-least four methods to replace String in Java according to JDK 1.6 documentation.

1. Replace method to replacesingle character in String

replace(char oldChar, char newChar)

This replace method in String takes one character and replaces all of its occurrence in provided
String with new character provided to it. Here is an String replace Example of changing character

String replaceSample = "This String replace Example shows how to replace one char from String";
String newString = replaceSample.replace('r', 't');

Output: This Stting teplace Example shows how to teplace one chat ftom Stting


You can see all occurrence of "r" has been replaced by "t".

Important points:
1. This replace method of String will return a new String object if there is a replace.
2. It will return same String objects if there is no matching char and there is no replace.
3. Replacement of String is Case Sensitive, so replacing "c" will only replace small case not Capital Case .

2. Replace method to replace character sequence in String

replace(CharSequence target, CharSequence replacement)

This String replace method replaces one character sequence with other.This method has added from JDK 1.5 onwards. Here is a String replace example of replacing character sequence form String

String replaceSample = "String replace Example of replacing Character Sequence";
String newString = replaceSample.replace("re", "RE");

Output : String REplace Example of REplacing Character Sequence

In this String replace Example, we have replaced "re" with "RE".

Important points:
1) This String replace method willthrow NullPointerException if either oldCharSequence or newCharSequence is null.
2) Replacement of Stringstarts from beginning and proceed towards end. So in a String "ccc" replacing "cc" with "d" will result in "dc" rather than "cd".


3. Replace method to replace all matched pattern in String

replaceAll(String regex, String replacement)

Good thing about replace method of String Class in Java is that it supports regular expression. With regex capability you can perform sophisticatedSearch on String and than replace characters. This String replace method replaces each matched substring with the replacement String provided. Let's see String replace example with regular expression:

String replaceSample = "String replace Example with regular expression";
String newString = replaceSample.replaceAll("^S","R");

Output: Rtring replace Example with regular expression

This String replace replaces any "S" wiht "R" if it comes at beginning of line "^" denotes beginning of line you can alsoapply pattern matching wildcards and charset while replacing String in Java.


Important points:
1. This String replace method will thro wPatternSyntaxException in case regular expression's syntax is not valid.

4. Replace method to replace first matched pattern in String

replaceFirst(String regex, String replacement)

This String replace method is similar to above method but it only replaces first occurrence of matching pattern instead of all occurrence. Very handy some time. Here is an example of String replace with replaceFirst() method.

String replaceSample = "String replace Example with replaceFirst";
String newString = replaceSample.replaceFirst("re","RE");

Output: String REplace Example with replaceFirst

You can see only first occurrence of "re" is replaced with "RE" while second occurrence remains same

That’s all on how to replace String in Java, search and replace is one of the most needed thing in String and having an idea of right way of doing it is good. These String replace examples are rather simple but you can make more sophisticated by using regular expression.


Other Java Tutorials



Read more: http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html#ixzz2ki3ClW3k
### Java ZPL Printer SDK Integration Tutorial For integrating with Zebra printers using ZPL (Zebra Programming Language), developers often rely on direct communication methods rather than an official SDK provided by Zebra. The most common approach involves sending raw ZPL commands directly to the printer through various interfaces such as USB, Ethernet, or Bluetooth. A typical method for achieving this in Java includes establishing a connection to the printer and then transmitting the ZPL string data. Below is an example demonstrating how to send ZPL code from a Java application: #### Establishing Connection Using Network Socket When connecting via TCP/IP, which allows remote printing over a network, here’s how it could be implemented: ```java import java.io.OutputStream; import java.net.Socket; public class ZplPrinter { private static final String PRINTER_IP = "192.168.1.10"; // Replace with your printer's IP address. private static final int PORT = 9100; // Standard port number used by many thermal label printers. public void printLabel(String zplData) throws Exception { try (Socket socket = new Socket(PRINTER_IP, PORT); OutputStream os = socket.getOutputStream()) { byte[] commandBytes = zplData.getBytes(); os.write(commandBytes); System.out.println("Print job sent successfully."); } } } ``` This snippet establishes a connection to the specified printer at `PRINTER_IP` on port `PORT`, sends the given ZPL instructions contained within `zplData`, and closes the stream afterward[^1]. To further enhance functionality, consider implementing error handling mechanisms like timeouts when attempting connections or retries upon failure scenarios. Additionally, exploring libraries specifically designed for interacting with hardware devices might offer higher-level abstractions simplifying tasks related to device management and communications[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值