String method output not understanding - java

From the below question I din't understand how the output has come. Could someone please explain me how did it come ?
public class mystery{
public static void main(String[] args) {
System.out.println(serios("DELIVER"));
}
public static String serios(String s)
{
String s1 = s.substring(0,1);
System.out.println(s1);
String s2 = s.substring(1, s.length() - 1);
System.out.println(s2);
String s3 = s.substring(s.length() - 1);
System.out.println(s3);
if (s.length() <= 3)
return s3 + s2 + s1;
else
return s1 + serios(s2) + s3;
}
}
Output:
D
ELIVE
R
E
LIV
E
L
I
V
DEVILER
Thanks !!

For this chunk of code
String s1 = s.substring(0,1);//this initializes s1 = D as Substring reads up to right before the ending index which is 1.
System.out.println(s1);//print s1
This chunk
String s2 = s.substring(1, s.length() - 1);//Starts where the previous chunk left off, ends right before the ending initializing s2 = ELIVE
System.out.println(s2);//print s2
Final Chunk
String s3 = s.substring(s.length() - 1);//This chunk starts from the end and captures R
System.out.println(s3);//print s3
These three chunks and their print statements will give you
D ELIVE R
Now let's move on.
The final return statement returns s1 + serios(s2) + s3. This is recursion, a function called within itself.
This recursion will run until the if condition is met. Finally printing out DELIVER
You can see a pattern to understand better.
DELIVER when run through the code is printed out like this D ELIVE R. The first and last letters are separated from the center of the word.
return s1 + serios(s2) + s3;
since s2 = ELIVE it will become equal to s. It will be split apart using substring just like DELIVER to become E LIV E setting
LIV = s2
s will now equal LIV, and be split apart and printed out as
L I V
Finally the length of s is equal to 3, so the if condition will run and print out DEVILER

apart of what subString is doing, I think your problem is about recursive behavior of the series method.
at first call u send "DELIVER".
at the following line you can see if the input param is grater than 3 the method call itself agin this time with s2. for the first iteration s2 = ELIVE.
if (s.length() <= 3)
return s3 + s2 + s1;
else
return s1 + serios(s2) + s3;
you can think about running series("ELIVE"); and for the same process you will see this time s2 will get "LIV" which the recursion do not happen again and if part will run.
if (s.length() <= 3)
return s3 + s2 + s1;
I hope this help you.

For this type of tasks, it helps to trace the method calls
public class mystery {
public static void main(String[] args)
{
serios("DELIVER", "");
}
public static String serios(String s, String indentation)
{
String s1 = s.substring(0, 1);
System.out.println(indentation + "\"" + s1 + "\" is the substring of \"" + s + "\" at 0");
String s2 = s.substring(1, s.length() - 1);
System.out.println(indentation + "\"" +s2 + "\" is the substring of \"" + s + "\" from 1 to " + (s.length() - 2));
String s3 = s.substring(s.length() - 1);
System.out.println(indentation + "\"" + s3 + "\" is the substring of \"" + s + "\" at " + (s.length() - 1));
if (s.length() <= 3)
return s3 + s2 + s1;
else
{
indentation += " ";
return s1 + serios(s2, indentation) + s3;
}
}
}
Output:
"D" is the substring of "DELIVER" at 0
"ELIVE" is the substring of "DELIVER" from 1 to 5
"R" is the substring of "DELIVER" at 6
"E" is the substring of "ELIVE" at 0
"LIV" is the substring of "ELIVE" from 1 to 3
"E" is the substring of "ELIVE" at 4
"L" is the substring of "LIV" at 0
"I" is the substring of "LIV" from 1 to 1
"V" is the substring of "LIV" at 2

Related

split String If get any capital letters

My String:
BByTTheWay .I want to split the string as B By T The Way BByTheWay .That means I want to split string if I get any capital letters and last put the main string as it is. As far I tried in java:
public String breakWord(String fileAsString) throws FileNotFoundException, IOException {
String allWord = "";
String allmethod = "";
String[] splitString = fileAsString.split(" ");
for (int i = 0; i < splitString.length; i++) {
String k = splitString[i].replaceAll("([A-Z])(?![A-Z])", " $1").trim();
allWord = k.concat(" " + splitString[i]);
allWord = Arrays.stream(allWord.split("\\s+")).distinct().collect(Collectors.joining(" "));
allmethod = allmethod + " " + allWord;
// System.out.print(allmethod);
}
return allmethod;
}
It givs me the output: B ByT The Way BByTTheWay . I think stackoverflow community help me to solve this.
You may use this code:
Code 1
String s = "BByTTheWay";
Pattern p = Pattern.compile("\\p{Lu}\\p{Ll}*");
String out = p.matcher(s)
.results()
.map(MatchResult::group)
.collect(Collectors.joining(" "))
+ " " + s;
//=> "B By T The Way BByTTheWay"
RegEx \\p{Lu}\\p{Ll}* matches any unicode upper case letter followed by 0 or more lowercase letters.
CODE DEMO
Or use String.split using same regex and join it back later:
Code 2
String out = Arrays.stream(s.split("(?=\\p{Lu})"))
.collect(Collectors.joining(" ")) + " " + s;
//=> "B By T The Way BByTTheWay"
Use
String s = "BByTTheWay";
Pattern p = Pattern.compile("[A-Z][a-z]*");
Matcher m = p.matcher(s);
String r = "";
while (m.find()) {
r = r + m.group(0) + " ";
}
System.out.println(r + s);
See Java proof.
Results: B By T The Way BByTTheWay
EXPLANATION
--------------------------------------------------------------------------------
[A-Z] any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z' (0 or more
times (matching the most amount possible))
As per requirements, you can write in this way checking if a character is an alphabet or not:
char[] chars = fileAsString.toCharArray();
StringBuilder fragment = new StringBuilder();
for (char ch : chars) {
if (Character.isLetter(ch) && Character.isUpperCase(ch)) { // it works as internationalized check
fragment.append(" ");
}
fragment.append(ch);
}
String.join(" ", fragment).concat(" " + fileAsString).trim(); // B By T The Way BByTTheWay

How to check If a multiline String contains another multiline String in Java?

1.I tried to use the contains function BUT it did not work, it only works when b = "30-10-1960\n" or b = "Posephine Esmerelda Bloggs\n". How to check if a contains b?
2.Here is the code I wrote.
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"30-10-1960\n";
System.out.println("a.contains(b)");
it works try this -
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n";
System.out.println(a.contains(b));
in your code there is some issue -
1. you used as a string literals in println method, it must be a reference.
2. what you are comparing is not same. In 'a' there is extra word 'birthday' that is missing in 'b'.
The correct string sequence i pasted in sample code.
I think the logic you want here is to assert that every line of the b string appears somewhere in the a string:
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"30-10-1960\n";
String[] lines = b.split("\n");
// now check each line
boolean all = true;
for (String line : lines) {
if (!a.contains(line)) {
all = false;
break;
}
}
if (all) {
System.out.println("MATCH");
}
else {
System.out.println("NO MATCH");
}
This prints:
MATCH
for the answer of the question how to find the two parts in b
String[] arr = b.split( "\n" );
int pos = a.indexOf( arr[0] + '\n' );
if( pos > -1 && a.indexOf( arr[1] + '\n', pos ) > -1 )
System.err.println( "found" );
+ '\n': finds the parts only if they end with a \n
if the check for the ending '\n' is unnecessary remove both + '\n'
if the parts may be unordered the pos argument can be omitted
without checking for the \n at the end or the order as in the chosen solution
String[] arr = b.split( "\n" );
if( a.indexOf( arr[0] ) > -1 && a.indexOf( arr[1] ) > -1 )
System.err.println( "found" );
the solution without checking is identical to the following
if( a.contains( arr[0] ) && a.contains( arr[1] ) )
System.err.println( "found" );
…because contains(s) returns indexOf(s.toString()) > -1

What does this quotation marks represent in System.out.println()?

I wonder why the double quotation marks is not shown in the actual output - just after the equal sign:
String word = "" + c1 + c2 + "ll";
The full code as follows:
public class InstantMethodsIndexOf
{
public void start()
{
String greeting = new String ("Hello World");
int position = greeting.indexOf('r');
char c1 = greeting.charAt(position + 2);
char c2 = greeting.charAt(position - 1);
**String word = "" + c1 + c2 + "ll";**
System.out.println(word);
}
}
When you pass "" to a String you are passing an empty String. You need to escape the quotation with a back slash if you want to print them.
Example:
String word = "\"" + c1 + c2 + "ll\"";
then System.out.println(word) will print:
"Hell"
As you can see I am escaping one double quotation at the beginning and another at the end
(Assuming c1 == 'H' and c2 == 'e')
The quotation mark does not appear because you have none being printed. What you have is an empty string being concatenated with other contents.
If you need the quotation mark, then you shoud do the following:
String word = "\"" + c1 + c2 + "ll";
It's a way to let Java know that it will be a string straight from the beginning, since "" is a String object of an empty string.
In your code, it doesn't really look useful. But following is an example where it would be:
int a=10, b=20;
String word = a + b + "he"; // word = "30he"
String word2 = "" + a + b + "he"; // word2 = "1020he"
I wonder why the double quotation marks is not shown in the actual
output - just after the equal sign:
String word = "" + c1 + c2 + "ll";
You are declaring a String that concatenates:
The empty String ""
c1
c2
The String literal "ll"
To show the quotes and make the code easier to read, try:
String word = '\u0022' + c1 + c2 + "ll"
which uses the unicode character value to print the double quote
I wonder why the double quotation marks is not shown in the actual
output - just after the equal sign:
In java String represented by the use of double quotes means the data between double quotes is considered as String value but if you want to include double quotes you have to use escape character \".
Moreover I suggest you to use StringBuilder and append your characters and String into it and use toString to print.
String str="ABC";//So value of String literal is ABC not "ABC"
String empty="";//is just empty but NOT Null
String quote="\"";//Here String has value " (One Double Quote)
This code
String greeting = "Hello World"; // <-- no need for new String()
int position = greeting.indexOf('r'); // <-- 8
char c1 = greeting.charAt(position + 2); // <-- 'd'
char c2 = greeting.charAt(position - 1); // <-- 'o'
String word = "" + c1 + c2 + "ll"; // <-- "" + 'd' + 'o' + "ll"
The empty String "" is used to coerce the arithmetic to a String, so it could also be written as
StringBuilder sb = new StringBuilder();
sb.append(c1).append(c2).append("ll");
String word = sb.toString();
or
StringBuilder sb = new StringBuilder("ll");
sb.insert(0, c2);
sb.insert(0, c1);
String word = sb.toString();
If you wanted to include double quotes in your word, your could escape them with a \\ or use a character -
char c1 = greeting.charAt(position + 2); // <-- 'd'
char c2 = greeting.charAt(position - 1); // <-- 'o'
String word = "\"" + c1 + c2 + "ll\""; // <-- "\"" + 'd' + 'o' + "ll\""
or
String word = "" + '"' + c1 + c2 + "ll" + '"';

Issue with output of java program involving string

class Blue_ManTest{
public static void main(String[] args){
String name = "I LOVE JAVAWORLD";
int index1 = name.indexOf(" ");
int index2 = name.lastIndexOf(" ");
String str1 = name.substring(0, index1);
String str2 = name.substring(index1 + 1, index1+ 5);
String str3 = name.substring(index2 + 5);
System.out.println(str3 + ", " + str1 + " " + str2 + ".");
}
}
I am having trouble figuring out what would be the output of this program I think I know it but I am not sure.
I did this I Love JavaWorld with 0 corresponding to j and 15 to D with 1 being the space between.
for str1 I get I
for str2 I get Love
but for str3 I get avaWorld
But str3 seems wrong to me as it would print out.
avaWorld, I Love.
Your str3 variable is taking a substring that starts at index2 + 5 where index2 is the index of the last space in your input string:
int index2 = name.lastIndexOf(" ");
That is, index2 is 6. And of course 6 + 5 is 11.

Replacing sub-string of a String with another String

I have a String
String str = (a AND b) OR (c AND d)
I tokenise with the help of code below
String delims = "AND|OR|NOT|[!&|()]+"; // Regular expression syntax
String newstr = str.replaceAll(delims, " ");
String[] tokens = newstr.trim().split("[ ]+");
and get String[] below
[a, b, c, d]
To each element of the array I add " =1" so it becomes
[a=1, b=1, c=1, d=1]
NOW I need to replace these values to the initial string making it
(a=1 AND b=1) OR (c=1 AND d=1)
Can someone help or guide me ? The initial String str is arbitrary!
This answer is based on #Michael's idea (BIG +1 for him) of searching words containing only lowercase characters and adding =1 to them :)
String addstr = "=1";
String str = "(a AND b) OR (c AND d) ";
StringBuffer sb = new StringBuffer();
Pattern pattern = Pattern.compile("[a-z]+");
Matcher m = pattern.matcher(str);
while (m.find()) {
m.appendReplacement(sb, m.group() + addstr);
}
m.appendTail(sb);
System.out.println(sb);
output
(a=1 AND b=1) OR (c=1 AND d=1)
Given:
String str = (a AND b) OR (c AND d);
String[] tokened = [a, b, c, d]
String[] edited = [a=1, b=1, c=1, d=1]
Simply:
for (int i=0; i<tokened.length; i++)
str.replaceAll(tokened[i], edited[i]);
Edit:
String addstr = "=1";
String str = "(a AND b) OR (c AND d) ";
String delims = "AND|OR|NOT|[!&|() ]+"; // Regular expression syntax
String[] tokens = str.trim().split( delims );
String[] delimiters = str.trim().split( "[a-z]+"); //remove all lower case (these are the characters you wish to edit)
String newstr = "";
for (int i = 0; i < delimiters.length-1; i++)
newstr += delimiters[i] + tokens[i] + addstr;
newstr += delimiters[delimiters.length-1];
OK now the explanation:
tokens = [a, b, c, d]
delimiters = [ "(" , " AND " , ") OR (" , " AND " , ") " ]
When iterating through delimiters, we take "(" + "a" + "=1".
From there we have "(a=1" += " AND " + "b" + "=1".
And on: "(a=1 AND b=1" += ") OR (" + "c" + "=1".
Again : "(a=1 AND b=1) OR (c=1" += " AND " + "d" + "=1"
Finally (outside the for loop): "(a=1 AND b=1) OR (c=1 AND d=1" += ")"
There we have: "(a=1 AND b=1) OR (c=1 AND d=1)"
How long is str allowed to be? If the answer is "relatively short", you could simply do a "replace all" for every element in the array. This obviously is not the most performance-friendly solution, so if performance is an issue, a different solution would be desireable.

Categories

Resources