I am trying take a string similar to this: 3A5o2n4t and expand it back to a string like this: AAAooooonntttt (the number in front of the letter is how many times the letter repeats)
I was trying to use Integer.parseInt() to get the number in front of the letter, but it grabs all of the numbers. Is there a way to grab one number at a time? Also, does my code look okay after that issue is resolved? Or am I missing a bit still?
public String runLengthDecoding(String str3) {
String convert = "";
int number = 0;
if (! str3.isEmpty()) {
convert = str3.charAt(0) + "";
}
for (int i = 0; i <= str3.length() - 1; i++) {
if (Character.isDigit(str3.charAt(i))) { //true or false, the current character is a digit
String temp = "" + str3.charAt(i); //if true, make that character a string
number = Integer.parseInt(temp); /*now store that character as a number (but I only want the current
number, not all the numbers in the string*/
System.out.println(number); /*Testing to see what number is, which is where I found it was
storing all the numbers */
String temp2 = str3.charAt(i + 1) + ""; //Its supposed to start making a string that prints the character in front of it
convert = temp2.repeat(number); //it will print the character however many times that number was stored as
}
}
return convert;
}
Also I have not yet learned how to use arrays, that is why I am not using an array.
Edited to:
- accommodate strings that has length more then 1. Example: 10AA
- accommodate input that starts with a string. Example: A5o
To solve this you have to get all the simultaneous digits, example if you have "55s", you have to get "55", That is why your code is incorrect since if you parseInt whenever you see a digit then it will immediately parse into 5, but the actual number is 55, thus you should accumulate the simultaneous digits first and only parseInt when you encounter the first non digit.
Refer to the code and comments for details:
public class Main {
public static void main(String[] args) {
System.out.println("Input: 3A5o2n4t => Output : " + runLengthDecoding("3A5o2n4t"));
System.out.println("Input: 3AA5o2n4t => Output : " + runLengthDecoding("3AA5o2n4t"));
System.out.println("Input: 10A5o2n4t => Output : " + runLengthDecoding("10A5o2n4t"));
System.out.println("Input: 10AA5o2n4t => Output : " + runLengthDecoding("10AA5o2n4t"));
System.out.println("Input: A5o => Output : " + runLengthDecoding("A5o"));
System.out.println("Input: AB5o => Output : " + runLengthDecoding("AB5o"));
}
public static String runLengthDecoding(String str3) {
String convert = "";
int number = 0;
String numberString = "";
String toBeRepeatedString = "";
boolean flag = false;
for (int i = 0; i <= str3.length() - 1; i++) {
char currentChar = str3.charAt(i);
if (Character.isDigit(currentChar)) { // true or false, the current character is a digit
numberString = numberString + currentChar; // store the possible integer
} else {
if (i + 1 < str3.length()) {
char nextChar = str3.charAt(i + 1); // check if the next char is a digit
if (!Character.isDigit(nextChar)) { // if not a digit then append toBeRepeatedString
if (i == 0 || i + 1 >= str3.length()) {
flag = true;
} else {
toBeRepeatedString += nextChar;
flag = false;
}
} else {
flag = true;
}
}
if (flag) {
toBeRepeatedString += currentChar;
// This will accomodate inputs "A3B";
if (!numberString.isEmpty()) {
number = Integer.parseInt(numberString); // parse the number of repeats
} else {
number = 1;
}
numberString = ""; // reset number
String temp2 = "";
// Repeat the currentChar
for (int j = 0; j < number; j++) {
temp2 += toBeRepeatedString;
}
convert = convert + temp2; // store it to the result
toBeRepeatedString = ""; // reset toBeRepeatedString
}
}
}
return convert;
}
}
Result:
Input: 3A5o2n4t => Output : AAAooooonntttt
Input: 3AA5o2n4t => Output : AAAAAAooooonntttt
Input: 10A5o2n4t => Output : AAAAAAAAAAooooonntttt
Input: 10AA5o2n4t => Output : AAAAAAAAAAAAAAAAAAAAooooonntttt
Input: A5o => Output : Aooooo
Input: AB5o => Output : ABooooo
Here is the best way of doing the above problem it will handle all your scenarios:
public static void main(String[] args) {
String input = "5a2s3T66e";
System.out.println("Input is: "+input+" and output is: "+expandingCondenseString(input));
}
private static String expandingCondenseString(String input){
StringBuilder result = new StringBuilder();
String size = "";
String value = "";
for (int i=0;i<input.length();i++){
if (Character.isDigit(input.charAt(i))) {
size = size + input.charAt(i);
} else {
value = value + input.charAt(i);
if(i+1<input.length() && !Character.isDigit(input.charAt(i+1))){
continue;
}
if(size.isEmpty()){
size = "1";
}
for (int j=0;j<Integer.parseInt(size);j++){
result.append(value);
}
size = "";
value = "";
}
}
return String.valueOf(result);
}
Related
I have this assignment that needs me to decompress a previously compressed string.
Examples of this would be
i4a --> iaaaa
q3w2ai2b --> qwwwaaibb
3a --> aaa
Here's what I've written so far:
public static String decompress(String compressedText)
{
char c;
char let;
int num;
String done = "";
String toBeDone = "";
String toBeDone2 = "";
if(compressedText.length() <= 1)
{
return compressedText;
}
if (Character.isLetter(compressedText.charAt(0)))
{
done = compressedText.substring(0,1);
toBeDone = compressedText.substring(1);
return done + decompress(toBeDone);
}
else
{
c = compressedText.charAt(0);
num = Character.getNumericValue(c);
let = compressedText.charAt(1);
if (num > 0)
{
num--;
toBeDone = num + Character.toString(let);
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone) + decompress(toBeDone2);
}
else
{
toBeDone2 = compressedText.substring(2);
return Character.toString(let) + decompress(toBeDone2);
}
}
}
My return values are absolutely horrendous.
"ab" yields "babb" somehow.
"a" or any 1 letter string string yields the right result
"2a" yields "aaaaaaaaaaa"
"2a3b" gives me "aaaabbbbbbbbbbbbbbbbbbbbbbbbbbaaabbbbaaaabbbbbbbbbbbbbbbbbbbbbbbbbb"
The only place I can see a mistake in would probably be the last else section, since I wasn't entirely sure on what to do once the number reaches 0 and I have to stop using recursion on the letter after it. Other than that, I can't really see a problem that gives such horrifying outputs.
I reckon something like this would work:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return String.join("", Collections.nCopies(Character.digit(c, 10), compressedText.substring(1, 2))) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
As you can see, the base case is when the compressed String has a length less than or equal to 1 (as you have it in your program).
Then, we check if the first character is a digit. If so, we substitute in the correct amount of characters, and continue with the recursive process until we reach the base case.
If the first character is not a digit, then we simply append it and continue.
Keep in mind that this will only work with numbers from 1 to 9; if you require higher values, let me know!
EDIT 1: If the Collections#nCopies method is too complex, here is an equivalent method:
if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Character.digit(c, 10); i++) {
sb.append(compressedText.charAt(1));
}
return sb.toString() + decompress(compressedText.substring(2));
}
EDIT 2: Here is a method that uses a recursive helper-method to repeat a String:
public static String decompress(String compressedText) {
if (compressedText.length() <= 1) {
return compressedText;
}
char c = compressedText.charAt(0);
if (Character.isDigit(c)) {
return repeatCharacter(compressedText.charAt(1), Character.digit(c, 10)) + decompress(compressedText.substring(2));
}
return compressedText.charAt(0) + decompress(compressedText.substring(1));
}
public static String repeatCharacter(char character, int counter) {
if (counter == 1) {
return Character.toString(character);
}
return character + repeatCharacter(character, counter - 1);
}
I've written a Reverse digit program but need to check this program to see if it is working correctly. What am I missing an if/else statement?
import java.util.*;
public class IT145_Homework_7_3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// input int parameter
System.out.print("Enter number to reverse: ");
//sets variables
int original = scanner.nextInt();
int reverse = 0;
int remainder;
//original number equals 542
while (original != 0) {
remainder = original % 10; //2 //4 //5
reverse = reverse * 10 + remainder; //2 //24 //245
original = original / 10; //54 //5 //0
}
//Prints out numbers in Reverse
System.out.println("Reverse of number is: " + reverse);
}
}
Here's one way to do the check, but you have to keep an int of the original before you change the original. I called it originalInt
// sets variables
int original = scanner.nextInt();
int originalInt = original; // Save it off here
// all of your code to run the reverse...
// Code to run the check...
String revStr = String.valueOf(reverse);
String orgStr = String.valueOf(originalInt);
// In case you are inputting negative ints
orgStr = orgStr.replace("-", "");
revStr = revStr.replace("-", "");
// remove all trailing zeros from original and check if they are equal
// This is for the cases where the input is '900' and your reverse is '9'
orgStr = orgStr.replaceAll("0*$", "");
boolean worked = true;
// if the lengths are equal, then check if the chars match in opposite directions.
if (revStr.length() == orgStr.length())
{
int len = orgStr.length();
for (int i = 0; i < len; i++)
{
if (orgStr.charAt(i) != revStr.charAt(len - (i+1)))
{
worked = false;
break;
}
}
}
else
{
worked = false;
}
System.out.println("Worked: " + worked);
EDIT: First code had bug.
it can also be done as
int no=scanner.nextInt();
StringBuffer sb= new StringBuffer(no+"");
System.out.println(Integer.parseInt(new String(sb.reverse())));
I have somehow got the output with the help of some browsing. But I couldn't understand the logic behind the code. Is there any simple way to achieve this?
public class LetterCount {
public static void main(String[] args)
{
String str = "aabbcccddd";
int[] counts = new int[(int) Character.MAX_VALUE];
// If you are certain you will only have ASCII characters, I would use `new int[256]` instead
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
counts[(int) charAt]++;
}
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
//System.out.println("Number of " + (char) i + ": " + counts[i]);
System.out.print(""+ counts[i] + (char) i + "");
}
}
}
There are 3 conditions which need to be taken care of:
if (s.charAt(x) != s.charAt(x + 1) && count == 1) ⇒ print the counter and character;
if (s.charAt(x) == s.charAt(x + 1)) ⇒ increase the counter;
if (s.charAt(x) != s.charAt(x + 1) && count >= 2) ⇒ reset to counter 1.
{
int count= 1;
int x;
for (x = 0; x < s.length() - 1; x++) {
if (s.charAt(x) != s.charAt(x + 1) && count == 1) {
System.out.print(s.charAt(x));
System.out.print(count);
}
else if (s.charAt(x)== s.charAt(x + 1)) {
count++;
}
else if (s.charAt(x) != s.charAt(x + 1) && count >= 2) {
System.out.print(s.charAt(x));
System.out.print(count);
count = 1;
}
}
System.out.print(s.charAt(x));
System.out.println(count);
}
The code is really simple.It uses the ASCII value of a character to index into the array that stores the frequency of each character.
The output is simply got by iterating over that array and which character has frequency greater than 1, print it accordingly as you want in the output that is frequency followed by character.
If the input string has same characters consecutive then the solution can be using space of O(1)
For example in your string aabbcc, the same characters are consecutive , so we can take advantage of this fact and count the character frequency and print it at the same time.
for (int i = 0; i < str.length(); i++)
{
int freq = 1;
while((i+1)<str.length()&&str.charAt(i) == str.charAt(i+1))
{++freq;++i}
System.out.print(freq+str.charAt(i));
}
You are trying to keep count of the number of times each character is found. An array is referenced by an index. For example, the ASCII code for the lowercase letter a is the integer 97. Thus the count of the number of times the letter a is seen is in counts[97]. After every element in the counts array has been set, you print out how many have been found.
This should help you understand the basic idea behind how to approach the string compression problem
import java.util.*;
public class LetterCount {
public static void main(String[] args) {
//your input string
String str = "aabbcccddd";
//split your input into characters
String chars[] = str.split("");
//maintain a map to store unique character and its frequency
Map<String, Integer> compressMap = new LinkedHashMap<String, Integer>();
//read every letter in input string
for(String s: chars) {
//java.lang.String.split(String) method includes empty string in your
//split array, so you need to ignore that
if("".equals(s))
continue;
//obtain the previous occurances of the character
Integer count = compressMap.get(s);
//if the character was previously encountered, increment its count
if(count != null)
compressMap.put(s, ++count);
else//otherwise store it as first occurance
compressMap.put(s, 1);
}
//Create a StringBuffer object, to append your input
//StringBuffer is thread safe, so I prefer using it
//you could use StringBuilder if you don't expect your code to run
//in a multithreaded environment
StringBuffer output = new StringBuffer("");
//iterate over every entry in map
for (Map.Entry<String, Integer> entry : compressMap.entrySet()) {
//append the results to output
output.append(entry.getValue()).append(entry.getKey());
}
//print the output on console
System.out.println(output);
}
}
class Solution {
public String toFormat(String input) {
char inChar[] = input.toCharArray();
String output = "";
int i;
for(i=0;i<input.length();i++) {
int count = 1;
while(i+1<input.length() && inChar[i] == inChar[i+1]) {
count+=1;
i+=1;
}
output+=inChar[i]+String.valueOf(count);
}
return output;
}
public static void main(String[] args) {
Solution sol = new Solution();
String input = "aaabbbbcc";
System.out.println("Formatted String is: " + sol.toFormat(input));
}
}
def encode(Test_string):
count = 0
Result = ""
for i in range(len(Test_string)):
if (i+1) < len(Test_string) and (Test_string[i] == Test_string[i+1]):
count += 1
else:
Result += str((count+1))+Test_string[i]
count = 0
return Result
print(encode("ABBBBCCCCCCCCAB"))
If you want to get the correct count considering the string is not in alphabetical order. Sort the string
public class SquareStrings {
public static void main(String[] args) {
SquareStrings squareStrings = new SquareStrings();
String str = "abbccddddbd";
System.out.println(squareStrings.manipulate(str));
}
private String manipulate(String str1) {
//convert to charArray
char[] charArray = str1.toCharArray();
Arrays.sort(charArray);
String str = new String(charArray);
StringBuilder stbuBuilder = new StringBuilder("");
int length = str.length();
String temp = "";
if (length > 1) {
for (int i = 0; i < length; i++) {
int freq = 1;
while (((i + 1) < length) && (str.charAt(i) == str.charAt(i + 1))) {
++freq;
temp = str.charAt(i) + "" + freq;
++i;
}
stbuBuilder.append(temp);
}
} else {
return str + "" + 1;
}
return stbuBuilder.toString();
}
}
Kotlin:
fun compressString(input: String): String {
if (input.isEmpty()){
return ""
}
var result = ""
var count = 1
var char1 = input[0]
for (i in 1 until input.length) {
val char2 = input[i]
if (char1 == char2) {
count++
} else {
if (count != 1) {
result += "$count$char1"
count = 1
} else {
result += "$char1"
}
char1 = char2
}
}
result += if (count != 1) {
"$count$char1"
} else {
"$char1"
}
return result
}
given string is
'_home sweet home__'
if user enter the mode as 0 then o/p should be 'home sweet home__'
if user enter the mode as 1 then o/p should be '_home sweet home'
if user enter the mode as 2 then o/p should be 'home sweet home'.
Code
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
System.out.println("Enter the StringMode");
String strMode= sc.nextLine();
switch()
{
}
i want to find total number of white spaces in the given string.
Do this to remove all the whitespaces. Then, subtract the length of the second string from the length of the first to determine the total number of whitespaces removed.
If you want to remove only the preceding whitespace, use "^\\s+". To remove trailing, use "\\s+$".
You could try something like this:
/**
* Remove white spaces from string according to mode
*
* #param str string
* #param mode mode 0=leading, 1=trailing, 2=leading+trailing
* #param result - result buffer
* #return number of white spaces removed
*/
public int removeWhiteSpacesByMode(String str, int mode, StringBuilder result) {
int n = 0;
switch(mode) {
case 0:
n = removeLeadingWhiteSpaces(str, result);
break;
case 1:
n = removeTrailingWhiteSpaces(str, result);
break;
case 2:
StringBuilder tmp = new StringBuilder();
n = removeTrailingWhiteSpaces(str, tmp);
n += removeLeadingWhiteSpaces(tmp.toString(), result);
break;
default:
throw new IllegalArgumentException("mode=" + mode);
}
return n;
}
private int removeTrailingWhiteSpaces(String str, StringBuilder result) {
int n = 0;
if(str != null && result != null) {
n = str.length()-1;
while(Character.isWhitespace(str.charAt(n))) {
n--;
}
n++;
for(int j = 0; j < n; j++) {
result.append(str.charAt(j));
}
n = str.length() - n;
}
return n;
}
private int removeLeadingWhiteSpaces(String str, StringBuilder result) {
int n = 0;
if(str != null && result != null) {
while(Character.isWhitespace(str.charAt(n))) {
n++;
}
for(int j = n; j < str.length(); j++) {
result.append(str.charAt(j));
}
}
return n;
}
It makes use a of the method Character#isWhitespace to check whether a character is white space or not and a StringBuilder to build the result. The return value is the number of white paces removed.
If you want to have a method to just count the white spaces in a string you can loop over the entire string, check each character using Character#isWhitespace and increment a variable if it return true.
Finally here is some testing:
#Test
public void removeWhiteSpacesByMode() {
String str = " home sweet home ";
StringBuilder result = null;
int numberOfWhiteSpacesRemoved = 0;
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, null);
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 0, result);
Assert.assertEquals(0, result.length());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
try {
result = new StringBuilder();
numberOfWhiteSpacesRemoved = 0;
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 4, result);
Assert.fail("mode 4 should not have been accepted");
} catch(IllegalArgumentException e) {
Assert.assertEquals("mode=4", e.getMessage());
Assert.assertEquals(0, result.length());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
}
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, result);
Assert.assertEquals("home sweet home ", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 1);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 1, result);
Assert.assertEquals(" home sweet home", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 2);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 2, result);
Assert.assertEquals("home sweet home", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 3);
}
Try this
StringTokenizer t = new StringTokenizer(str," ");
result = t.nextToken();
Boolean first = str.toCharArray()[0]==' ';
Boolean last = str.toCharArray()[str.length()-1]==' ';
while(t.hasMoreTokens())
{
result += " " + t.nextToken();
}
switch(strMode)
{
case 0 : if(last) result += " ";
break;
case 1 : if(first) result = " " + result;
break;
}
System.out.println(result);
A regex-based solution to capture your whitespaces and then rebuild the string according to the mode you need. No loops but requires some knowledge.
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
System.out.println("Enter the StringMode");
int strMode= sc.nextInt();
Pattern pattern = Pattern.compile("^(?<leadingWs>\\s*)(?<text>.+?)(?<trailingWs>\\s*)$");
Matcher matcher = pattern.matcher(str);
matcher.matches(); // should match always
String result = "";
switch(strMode)
{
case 0:
result = matcher.group("text") + matcher.group("trailingWs");
break;
case 1:
result = matcher.group("leadingWs") + matcher.group("text");
break;
case 2:
result = matcher.group("text");
break;
default:
break;
}
System.out.println("Cleared string: \"" + result + "\"");
System.out.println("Leading whitespace characters: " + matcher.group("leadingWs").length());
System.out.println("Trailing whitespace characters: " + matcher.group("trailingWs").length());
}
It uses named capturing groups to extract your whitespace and reluctant quantifier to get all the text before trailing whitespace characters. See Pattern documentation for capturing groups and this tutorial to get how quantifiers work.
A simple way :
private static String truncateSpace(String text, int mode)
{
if(mode==0 || mode==2)
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ') {
text = text.substring(i, text.length());
break;
}
}
if(mode==1 || mode==2)
for (int i = text.length()-1; i > 0; i--) {
if (text.charAt(i) != ' ') {
text = text.substring(0, i+1);
break;
}
}
return text;
}
I have this code:
String s = "A very long string containing " +
"many many words and characters. " +
"Newlines will be entered at spaces.";
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 20)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
The output of the code is:
A very long string containing
many many words and
characters. Newlines
will be entered at spaces.
The above code is wrapping the string after the next space of every 30 characters, but I need to wrap the string after the previous space of every 30 characters, like for the first line it will be:
A very long string
And the 2nd line will be
containing many
Please give some proper solution.
You can use Apache-common's WordUtils.wrap().
Use lastIndexOf instead of indexOf, e.g.
StringBuilder sb = new StringBuilder(s);
int i = 0;
while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
This will produce the following output:
A very long string
containing many
many words and
characters.
Newlines will be
entered at spaces.
You can try the following:
public static String wrapString(String s, String deliminator, int length) {
String result = "";
int lastdelimPos = 0;
for (String token : s.split(" ", -1)) {
if (result.length() - lastdelimPos + token.length() > length) {
result = result + deliminator + token;
lastdelimPos = result.length() + 1;
}
else {
result += (result.isEmpty() ? "" : " ") + token;
}
}
return result;
}
call as wrapString("asd xyz afz","\n",5)
I know it's an old question, but . . . Based on another answer I found here, but can't remember the posters name. Kuddos to him/her for pointing me in the right direction.
public String truncate(final String content, final int lastIndex) {
String result = "";
String retResult = "";
//Check for empty so we don't throw null pointer exception
if (!TextUtils.isEmpty(content)) {
result = content.substring(0, lastIndex);
if (content.charAt(lastIndex) != ' ') {
//Try the split, but catch OutOfBounds in case string is an
//uninterrupted string with no spaces
try {
result = result.substring(0, result.lastIndexOf(" "));
} catch (StringIndexOutOfBoundsException e) {
//if no spaces, force a break
result = content.substring(0, lastIndex);
}
//See if we need to repeat the process again
if (content.length() - result.length() > lastIndex) {
retResult = truncate(content.substring(result.length(), content.length()), lastIndex);
} else {
return result.concat("\n").concat(content.substring(result.length(), content.length()));
}
}
//Return the result concatenating a newline character on the end
return result.concat("\n").concat(retResult);;
//May need to use this depending on your app
//return result.concat("\r\n").concat(retResult);;
} else {
return content;
}
}
public static void main(String args[]) {
String s1="This is my world. This has to be broken.";
StringBuffer buffer=new StringBuffer();
int length=s1.length();
int thrshld=5; //this valueis threshold , which you can use
int a=length/thrshld;
if (a<=1) {
System.out.println(s1);
}else{
String split[]=s1.split(" ");
for (int j = 0; j < split.length; j++) {
buffer.append(split[j]+" ");
if (buffer.length()>=thrshld) {
int lastindex=buffer.lastIndexOf(" ");
if (lastindex<buffer.length()) {
buffer.subSequence(lastindex, buffer.length()-1);
System.out.println(buffer.toString());
buffer=null;
buffer=new StringBuffer();
}
}
}
}
}
this can be one way to achieve
"\n" makes a wordwrap.
String s = "A very long string containing \n" +
"many many words and characters. \n" +
"Newlines will be entered at spaces.";
this will solve your problem