Java - StringWriter write(String str,int off,int len) method
Description
The Java StringWriter write(String str,int off,int len) method writes a portion of a string.
Declaration
Following is the declaration for java.io.StringWriter.write(String str,int off,int len) method.
public void write(String str,int off,int len)
Parameters
str − String to be written.
off − Offset from which to start writing characters.
len − Number of characters to write.
Return Value
This method does not return a value.
Exception
NA
Example - Usage of StringWriter write(String str,int off,int len) method
The following example shows the usage of StringWriter write(String str,int off,int len) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
String s = "Hello World";
// create a new writer
StringWriter sw = new StringWriter();
// write strings
sw.write(s, 0, 4);
sw.write(s, 5, 6);
// print result by converting to string
System.out.println("" + sw.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result −
Hell World
Example - Write a Substring from a String
The following example shows the usage of StringWriter write(String str,int off,int len) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter writer = new StringWriter();
String str = "WelcomeToJava";
writer.write(str, 7, 4); // Writes "ToJa"
System.out.println("Output: " + writer.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result−
Output: ToJa
Explanation
The string "WelcomeToJava" has characters at index 7 to 10: 'T', 'o', 'J', 'a'.
write(str, 7, 4) writes "ToJa" to the StringWriter.
Example - Extract and Write a Word
The following example shows the usage of StringWriter write(String str,int off,int len) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter writer = new StringWriter();
String sentence = "Java programming is powerful";
writer.write(sentence, 5, 11); // Writes "programming"
System.out.println("Result: " + writer.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result−
Result: programming
Explanation
The string "Java programming is powerful" starts the word "programming" at index 5.
Length = 11 → captures "programming".
write(sentence, 5, 11) writes "programming" to the buffer.