Remove white space from string without using trim method? - java

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;
}

Related

Put a space every 5 characters without using regex or StringBuilder

I want a user to put in a sentence with the scanner class.
Make sure to filter out all the spaces (for example the sentence: this is a test becomes thisisatest)
And then print out that sentence with a for loop with a space every 5 characters
(for example thisi sates t).
This is what i have so far
import java.util.Scanner;
public class BlockText {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Give your sentence: ");
String sentence = s.nextLine();
String nospace = sentence.replace(" ", "");
String out = "";
for (int i = 5; i < nospace.length(); i+=5) {
out += nospace.replaceAll( nospace.substring(i) , " ");
}
System.out.println("Sentence without spaces: " + nospace);
System.out.println("This gives: " + out);
}
}
but I have the issue that he repeats certain characters and removes others.
Like you can see underneath after "this gives:"
run:
Give your sentence:
this is a test
Sentence without spaces: thisisatest
This gives: thisi hisisa es
BUILD SUCCESSFUL (total time: 8 seconds)
Can someone help me out? Like I said in the titel, I want to accomplish this with a for loop and without using regex or StringBuilder.
You should really use a StringBuilder here, because appending strings with += in a loop is very inefficient.
Without a string builder, you can do something like this:
private static String addSpacesEvery5(String s) {
String out = "";
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
out += " "; // this will run once every five iterations, except the first one
}
out += s.charAt(i);
}
return out;
}
Or more efficiently without +=:
private static String addSpacesEvery5(String s) {
// s.length() / 5 is how many spaces we will add
char[] charArray = new char[s.length() + s.length() / 5];
int currentPos = 0;
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
charArray[currentPos] = ' ';
currentPos++;
}
charArray[currentPos] = s.charAt(i);
currentPos++;
}
return new String(charArray);
}
And then you can use it in your main method like this:
Scanner s = new Scanner(System.in);
System.out.println("Give your sentence: ");
String sentence = s.nextLine();
String nospace = sentence.replace(" ", "");
String out = addSpacesEvery5(nospace);
System.out.println("Sentence without spaces: " + nospace);
System.out.println("This gives: " + out);
With a string builder, the addSpacesEvery5 could be rewritten as:
private static String addSpacesEvery5(String s) {
StringBuilder out = new StringBuilder();
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
out.append(" ");
}
out.append(s.charAt(i));
}
return out.toString();
}
Here is one relatively simple and faster:
String tmp = new String();
int len = str.length();
int remOdds = len % 5;
int i = 0;
while (i < len - remOdds)
{
tmp = tmp.concat(str.substring(i, i + 5));
i += 5;
if (i < len)
{
tmp += " ";
}
}
while (i < len)
{
tmp += str.charAt(i);
i++;
}
str = tmp;

Expanding a condensed string

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);
}

parsing/converting task with characters and numbers within

It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn

Java String ReplaceFirst

I am reading in a string
Is Mississippi a State where there are many systems.
I would like to replace the 1st "s" or "S" in each word with "t" or "T" (i.e keeping the same case)...so that the output is:
It Mitsissippi a Ttate where there are many tystems.
I have tried
s= s.replaceFirst("(?i)S", "t"); [which of course didn't work]
and have experimented trying to split the string using a
string [] .split(Pattern.quote("\\s")) then trying to figure out how to replaceFirst() each element of the array and then return the values back to a string [but couldn't figure out the right way of doing it].
I thought \\G might help to restart at the next word but have gotten no where. Any help using these 3 methods is appreciated.
One option would be to split the string into words, and then use String.replaceFirst() on each word to replace the first occurrence of s with t (or any other letter you want):
Update:
I refactored my solution to find the first occurrence of any s (upper or lower case), and to apply the appropriate conversion on it.
String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder("");
for (int i=0; i < parts.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int index = parts[i].toLowerCase().indexOf('s');
if (index >= 0 && parts[i].charAt(index) == 's') {
sb.append(parts[i].replaceFirst("s", "t"));
}
else {
sb.append(parts[i].replaceFirst("S", "T"));
}
}
System.out.println(sb.toString());
Output:
It Mitsissippi a Ttate where there are many tystems.
Approach-1: Without using replace and split method for better performance.
String str = "Is Mississippi a State where there are many systems.";
System.out.println(str);
char[] cArray = str.toCharArray();
boolean isFirstS = true;
for (int i = 0; i < cArray.length; i++) {
if ((cArray[i] == 's' || cArray[i] == 'S') && isFirstS) {
cArray[i] = (cArray[i] == 's' ? 't' : 'T');
isFirstS = false;
} else if (Character.isWhitespace(cArray[i])) {
isFirstS = true;
}
}
str = new String(cArray);
System.out.println(str);
EDIT: Approach2: As you need to use replaceFirst method and you dont want to use StringBuilder here is an option for you:
String input = "Is Mississippi a State where there are many Systems.";
String[] parts = input.split(" ");
String output = "";
for (int i = 0; i < parts.length; ++i) {
int smallSIndx = parts[i].indexOf("s");
int capSIndx = parts[i].indexOf("S");
if (smallSIndx != -1 && (capSIndx == -1 || smallSIndx < capSIndx))
output += parts[i].replaceFirst("s", "t") + " ";
else
output += parts[i].replaceFirst("S", "T") + " ";
}
System.out.println(output); //It Mitsissippi a Ttate where there are many Tystems.
Note: I prefer approach 1 because it has no overhead for the method replaceFisrt and split , String append or concat
Use below amendment to Tim Biegeleisen's answer (before editing his post)
String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder("");
for (String part : parts) {
sb.append(part.replaceFirst("s", "t").replaceFirst("S", "T"));
sb.append(" ");
}
System.out.println(sb.toString());
Edit - You can use concat()
String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
String output = "";
for (String part : parts) {
output = output.concat(part.replaceFirst("s", "t").replaceFirst("S", "T") + " ");
}
System.out.println(output);
Update
String input = "Is Mississippi a State where there are many Systems.";
String[] parts = input.split(" ");
//StringBuilder sb = new StringBuilder("");
String output = "";
for (String part : parts) {
output = output.concat(part.replaceFirst("s", "t") + " ");
}
String[] parts2 = output.split(" ");
output = "";
for (String part : parts2) {
output = output.concat(part.replaceFirst("S", "T") + " ");
}
System.out.println(output);
I've created a method that -
is general purpose,
doesn't use replace or split, and
only uses one loop.
The following is my code snippet:
public static String replaceFirstOccurance(String sentence, char toChange, char changeWith) {
StringBuilder temp = new StringBuilder();
boolean changed = false;
for (int i = 0; i < sentence.length(); i++) {
if (!changed) {
if (sentence.charAt(i) == toChange) {
temp.append(changeWith);
changed = true;
} else if (sentence.charAt(i) == Character.toUpperCase(toChange)) {
temp.append(Character.toUpperCase(changeWith));
changed = true;
} else {
temp.append(sentence.charAt(i));
}
} else {
if (sentence.charAt(i) == ' ') {
changed = false;
}
temp.append(sentence.charAt(i));
}
}
return temp.toString();
}
My method would be less dependent on those string methods you've mentioned.
String phrase;
String [] parts = phrase.split(" ");
for (int i = 0; i < parts.length; i++ ) {
for (int j = 0; j < parts[i].length(); j++) {
if (parts[i].charAt(j) == 's') {
parts[i] = "t" + parts[i].substring(1);
break;
} else if (parts[i].charAt(0) == 'S') {
parts[i] = "T" + parts[i].substring(1);
break;
}
}
}
String modifiedPhrase = "";
for (int i = 0; i < parts.length; i++ ) {
modifiedPhrase += parts[i] + " ";
}
There is also a nice, compact, stream-based solution for that:
String result = Stream.of(s.split(" "))
.map(t -> t.replaceFirst("s", "t"))
.map(t -> t.replaceFirst("S", "T"))
.collect(Collectors.joining(" "));
String ss = "Is Mississippi a State where there are many systems.";
String out = "";//replaced string
for (String s : ss.split(" ")) {
int index = s.toUpperCase().indexOf('S');
out += (s.replaceFirst("[s,S]", index!= -1 && s.charAt(index) == 'S'
? "T" : "t")) + " ";
}
System.out.println(out);

Wrap the string after a number of characters word-wise in Java

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

Categories

Resources