Is it possible to display strings with new line inline - java

I have 2 strings
String str1 = "FIRST \n SECOND"
String str2 = "FIRST \n SECOND"
Is it possible for it to be displayed like this?
FIRST FIRST
SECOND SECOND

I do not think that you can do that with simple print statements.
What you can try, on the other hand, would be to have a list of string builders, one for each line. You would then split the string by \n and you place each item in the array in the next string builder.
Once that you would have finished, you would then simply need to traverse the list of string builders and print the content.
So basically (untested code, should give you an idea of what needs doing though):
List<StringBuilders> list = new ArrayList<>();
String str = '...';
String[] parsedLine = str.split("\\n");
for(int i = 0; i < parsedLine.length;i++) {
if(list.size() <= i) list.add(new StringBuilder());
list.get(i).append(parsedLine + "\t");
}
for(StringBuilder sb : list) {
System.out.println(sb.toString());
}

You May use first split and rejoin it using white space. it will work sure.
String finalString = "";
String[] finalStringArray = inputString.split("[\\n]+");
for(int i = 0; i<finalStringArray.lengh; i++){
finalString = finalString+" "+finalStringArray[i];
}

Related

Java - Make character after space uppercase?

I'm trying to have the letter after every space turn uppercase. Can someone tell me what's wrong with the following method? Given phrase "this is a test" it returns "ThIs Is A TesT" instead of "this Is A Test"
public String toTitleCase(String phrase) {
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
phrase = phrase.replace(phrase.substring(i+1,i+2),phrase.substring(i+1,i+2).toUpperCase());
}
}
return phrase;
}
The problem in your code is that String.replace replaces each target character present in the String, and not only the one you want.
You could work directly on an array of chars instead of on the String:
public static String toTitleCase(String phrase) {
// convert the string to an array
char[] phraseChars = phrase.toCharArray();
for (int i = 0; i < phraseChars.length - 1; i++) {
if(phraseChars[i] == ' ') {
phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
}
}
// convert the array to string
return String.valueOf(phraseChars);
}
It's replacing all t, try below code.
It will help you.
String phrase="this is a test";
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
System.out.println(phrase.substring(i+1,i+2));
phrase = phrase.replace(phrase.substring(i,i+2),phrase.substring(i,i+2).toUpperCase());
}
}
System.out.println(phrase);
Use streams (or split) to split your string into parts, don't do it manually using substring.
Try below code
String test = "this is a test";
UnaryOperator<String> capitalize = str ->
str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();
String result =
Stream.of(
test.split(" ")
).map(capitalize)
.collect(
Collectors.joining(" ")
);
System.out.println(result);
Output: This Is A Test
When you replace a substring it will replace the each occurrence of that substring - which is not necessarily the one you are trying to replace. This is why it is replacing letters inside words.
Switching to a StringBuilder here to poke individual characters. Note that we don't traverse the entire String because there is no next-character to capitalize at the last character.
public String toTitleCase(String phrase) {
StringBuilder sb = new StringBuilder(phrase);
for (int index = 0 ; index < phrase.length - 1 ; ++index) {
if (sb.charAt(index) == ' ') {
sb.setCharAt(index + 1, Character.toUppercase(sb.charAt(index + 1)));
}
}
return sb.toString();
}
If a letter is first in any word, it will be replaced everywhere. In your case, all t,i and a will be uppercase.
Taking example for is. It is find a space before. Than in if body, what actually happen:
phrase = phrase.replace("i","I");
And all i are replaced with I.
String class cannot replace at a specific position.
You have to options:
using StringBuilder which can replace at a specific position.
String toTitleCase(String phrase) {
StringBuilder sb= new StringBuilder(phrase);
for (int i=0; i<phrase.length(); i++) {
if(i==0 || phrase.charAt(i-1)==' ') {
sb.replace(i,i+1,phrase.substring(i,i+1).toUpperCase());
}
}
return sb.toString();
}
or with stream, which is the method I prefer because is one-line. This way you don't preserve white-spaces( multiple consecutive white-spaces will be replaced with only one space), but usually you want this.
Arrays.asList(phrase.split("\\s+")).stream().map(x->x.substring(0,1).toUpperCase()+x.substring(1)).collect(Collectors.joining(" "));

How to find the last word in a string

I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.
I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!
You can do this:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
and you've got your last word.
You are splitting the original string at every space and storing the substrings in an array using the String#split method.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
Output:
Wines
String#lastIndexOf and String#substring are your friends here.
chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);
You can use: (if you are not familiar with arrays or unusual methods)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}
you just need to traverse the input string from tail when first find blank char stop traverse work and return the word.a simple code like this:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}
You could try:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));

How to convert/sort a String based on two symbols in Java?

I have the following string:
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
And I'm trying to convert it to:
String converted = "aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz";
To be somehow sorted. This is what I have tried so far:
String[] parts = string.split("\\n");
List<String[]> list = new ArrayList<>();
for(String part : parts) {
list.add(part.split(","));
}
for(int i = 0, j = i + 1, k = j + 1; i < list.size(); i++) {
String[] part = list.get(i);
System.out.println(part[i]);
}
So I managed to get first element from each "unit" separately. But how to get all and order them so I get that result?
Can this be even simpler using Java8?
Thanks in advance!
I guess one way to do it would be:
String result = Arrays.stream(string.split("\\n"))
.map(s -> {
String[] tokens = s.split(",");
Arrays.sort(tokens);
return String.join(",", tokens);
})
.collect(Collectors.joining("\\n"));
System.out.println(result); // aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz
Just notice that in case your patterns are more complicated than \n or , - it is a good idea to extract those an separate Pattern(s)
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
String converted = Arrays.stream(string.split("\\n"))
.map(s -> Arrays.stream(s.split(","))
.sorted()
.collect(Collectors.joining(",")))
.collect(Collectors.joining("\\n"));
You can have it the old fashioned way without the use of Java 8 like this:
public static void main(String[] args) {
String s = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
System.out.println(sortPerLine(s));
}
public static String sortPerLine(String lineSeparatedString) {
// first thing is to split the String by the line separator
String[] lines = lineSeparatedString.split("\n");
// create a StringBuilder that builds up the sorted String
StringBuilder sb = new StringBuilder();
// then for every resulting part
for (int i = 0; i < lines.length; i++) {
// split the part by comma and store it in a List<String>
String[] l = lines[i].split(",");
// sort the array
Arrays.sort(l);
// add the sorted values to the result String
for (int j = 0; j < l.length; j++) {
// append the value to the StringBuilder
sb.append(l[j]);
// append commas after every part but the last one
if (j < l.length - 1) {
sb.append(", ");
}
}
// append the line separator for every part but the last
if (i < lines.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
But still, Java 8 should be preferred in my opinion, so stick to one of the other answers.
The Pattern class gives you a possibility to stream directly splitted Strings.
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
Pattern commaPattern = Pattern.compile(",");
String sorted = Pattern.compile("\n").splitAsStream(string)
.map(elem -> commaPattern.splitAsStream(elem).sorted().collect(Collectors.joining(",")))
.collect(Collectors.joining("\n"));

Split string after every 2 words and store into list

I have a string of words as follows:
String words = "disaster kill people action scary seriously world murder loose world";
Now, I wish to split every 2 words and store them into a list so that it will produce something like:
[disaster kill, people action, scary seriously,...]
The problem with my code is that it will split whenever it encounters a space. How do I modify it so that it will only be added into the list if it only encounters every 2nd space, preserving the space after each word)
My code:
ArrayList<String> wordArrayList = new ArrayList<String>();
for(String word : joined.split(" ")) {
wordArrayList.add(word);
}
Thanks.
Use this regular expression: (?<!\\G\\S+)\\s.
PROOF:
String words = "disaster kill people action scary seriously world murder loose world";
String[] result = words.split("(?<!\\G\\S+)\\s");
System.out.printf("%s%n", Arrays.toString(result));
And the result:
[disaster kill, people action, scary seriously, world murder, loose world]
Your loop should leave you with an ArrayList<String> that has each word, right? All you need to do now is iterate through that list and combine words together in sets of twos.
ArrayList<String> finalList = new ArrayList<String>();
for (int i = 0; i < wordArrayList.Size(); i+=2) {
if (i + 1 < wordArrayList.Size()
finalList.add(wordArrayList.get(i) + " " + wordArrayList.get(i + 1);
}
This should take your split words and add them to the list with spaces so that they look like your desired output.
I was looking for splitting a string after 'n' words.
So I modify the above solution.
private void spiltParagraph(int splitAfterWords, String someLargeText) {
String[] para = someLargeText.split(" ");
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < para.length; i += splitAfterWords) {
if (i + (splitAfterWords - 1) < para.length) {
StringBuilder compiledString = new StringBuilder();
for (int f = i; f <= i + (splitAfterWords - 1); f++) {
compiledString.append(para[f] + " ");
}
data.add(compiledString.toString());
}
}
}
I run into this problem today, adding an extra difficulty that is to write this solution in Scala. So, I needed to write a recursive solution that looks like:
val stringToSplit = "THIS IS A STRING THAT WE NEED TO SPLIT EVERY 2 WORDS"
#tailrec
def obtainCombinations(
value: String,
elements: List[String],
res: List[String]
): List[String] = {
if (elements.isEmpty)
res
else
obtainCombinations(elements.head, elements.tail, res :+ value + ' ' + elements.head)
}
obtainCombinations(
stringToSplit.split(' ').head,
stringToSplit.split(' ').toList.tail,
List.empty
)
The output will be:
res0: List[String] = List(THIS IS, IS A, A STRING, STRING THAT, THAT WE, WE NEED, NEED TO, TO SPLIT, SPLIT EVERY, EVERY 2, 2 WORDS)
Porting this to Java would be:
String stringToSplit = "THIS IS A STRING THAT WE NEED TO SPLIT EVERY 2 WORDS";
public ArrayList<String> obtainCombinations(String value, List<String> elements, ArrayList<String> res) {
if (elements.isEmpty()) {
return res;
} else {
res.add(value + " " + elements.get(0));
return obtainCombinations(elements.get(0), elements.subList(1, elements.size()), res);
}
}
ArrayList<String> result =
obtainCombinations(stringToSplit.split(" ")[0],
Arrays.asList(stringToSplit.split(" ")),
new ArrayList<>());

How to Check for Deleted Words Between 2 Sentences in Java

What's the best approach in Java if you want to check for words that were deleted from sentence A in sentence B. For example:
Sentence A: I want to delete unnecessary words on this simple sentence.
Sentence B: I want to delete words on this sentence.
Output: I want to delete (unnecessary) words on this (simple) sentence.
where the words inside the parenthesis are the ones that were deleted from sentence A.
Assuming order doesn't matter: use commons-collections.
Use String.split() to split both sentences into arrays of words.
Use commons-collections' CollectionUtils.addAll to add each array into an empty Set.
Use commons-collections' CollectionUtils.subtract method to get A-B.
Assuming order and position matters, this looks like it would be a variation of the Longest Common Subsequence problem, a dynamic programming solution.
wikipedia has a great page on the topic, there's really too much for me to outline here
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Everyone else is using really heavy-weight algorithms for what is actually a very simple problem. It could be solved using longest common subsequence, but it's a very constrained version of that. It's not a full diff; it only includes deletes. No need for dynamic programming or anything like that. Here's a 20-line implementation:
private static String deletedWords(String s1, String s2) {
StringBuilder sb = new StringBuilder();
String[] words1 = s1.split("\\s+");
String[] words2 = s2.split("\\s+");
int i1, i2;
i1 = i2 = 0;
while (i1 < words1.length) {
if (words1[i1].equals(words2[i2])) {
sb.append(words1[i1]);
i2++;
} else {
sb.append("(" + words1[i1] + ")");
}
if (i1 < words1.length - 1) {
sb.append(" ");
}
i1++;
}
return sb.toString();
}
When the inputs are the ones in the question, the output matches exactly.
Granted, I understand that for some inputs there are multiple solutions. For example:
a b a
a
could be either a (b) (a) or (a) (b) a and maybe for some versions of this problem, one of these solutions is more likely to be the "actual" solution than the other, and for those you need some recursive or dynamic programming approach... but let's not make it too much more complicated than what Israel Sato originally asked for!
String a = "I want to delete unnecessary words on this simple sentence.";
String b = "I want to delete words on this sentence.";
String[] aWords = a.split(" ");
String[] bWords = b.split(" ");
List<String> missingWords = new ArrayList<String> ();
int x = 0;
for(int i = 0 ; i < aWords.length; i++) {
String aWord = aWords[i];
if(x < bWords.length) {
String bWord = bWords[x];
if(aWord.equals(bWord)) {
x++;
} else {
missingWords.add(aWord);
}
} else {
missingWords.add(aWord);
}
}
This works well....for updated strings also
updated strings enclosed with square brackets.
import java.util.*;
class Sample{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
List<String> flist = Arrays.asList(str1.split("\\s+"));
List<String> slist = Arrays.asList(str2.split("\\s+"));
List<String> completedString = new ArrayList<String>();
String result="";
String updatedString = "";
String deletedString = "";
int i=0;
int startIndex=0;
int endIndex=0;
for(String word: slist){
if(flist.contains(word)){
endIndex = flist.indexOf(word);
if(!completedString.contains(word)){
if(deletedString.isEmpty()){
for(int j=startIndex;j<endIndex;j++){
deletedString+= flist.get(j)+" ";
}
}
}
startIndex=endIndex+1;
if(!deletedString.isEmpty()){
result += "("+deletedString.substring(0,deletedString.length()-1)+") ";
deletedString="";
}
if(!updatedString.isEmpty()){
result += "["+updatedString.substring(0,updatedString.length()-1)+"] ";
updatedString="";
}
result += word+" ";
completedString.add(word);
if(i==slist.size()-1){
endIndex = flist.size();
for(int j=startIndex;j<endIndex;j++){
deletedString+= flist.get(j)+" ";
}
startIndex = endIndex+1;
}
}
else{
if(i == 0){
boolean boundaryCheck = false;
for(int j=i+1;j<slist.size();j++){
if(flist.contains(slist.get(j))){
endIndex=flist.indexOf(slist.get(j));
boundaryCheck=true;
break;
}
}
if(!boundaryCheck){
endIndex = flist.size();
}
if(!completedString.contains(word)){
for(int j=startIndex;j<endIndex;j++){
deletedString+= flist.get(j)+" ";
}
}
startIndex = endIndex+1;
}else if(i == slist.size()-1){
endIndex = flist.size();
if(!completedString.contains(word)){
for(int j=startIndex;j<endIndex;j++){
deletedString+= flist.get(j)+" ";
}
}
startIndex = endIndex+1;
}
updatedString += word+" ";
completedString.add(word);
}
i++;
}
if(!deletedString.isEmpty()){
result += "("+deletedString.substring(0,deletedString.length()-1)+") ";
}
if(!updatedString.isEmpty()){
result += "["+updatedString.substring(0,updatedString.length()-1)+"] ";
}
System.out.println(result);
}
}
This is basically a differ, take a look at this:
diff
and the root algorithm:
Longest common subsequence problem
Here's a sample Java implementation:
http://introcs.cs.princeton.edu/java/96optimization/Diff.java.html
which compares lines. The only thing you need to do is split by word instead of by line or alternatively put each word of both sentences in a separate line.
If e.g. on Linux, you can actually see the results of the latter option using diff program itself before you even write any code, try this:
$ echo "I want to delete unnecessary words on this simple sentence."|tr " " "\n" > 1
$ echo "I want to delete words on this sentence."|tr " " "\n" > 2
$ diff -uN 1 2
--- 1 2012-10-01 19:40:51.998853057 -0400
+++ 2 2012-10-01 19:40:51.998853057 -0400
## -2,9 +2,7 ##
want
to
delete
-unnecessary
words
on
this
-simple
sentence.
The lines with - in front are different (alternatively, it would show + if the lines were added into sentence B that were not in sentence A). Try it out to see if that fits your problem.
Hope this helps.

Categories