I have 2 classes, NonEmptyTree and EmptyTree that implement the Tree interface. toString() method in NonEmptyTree class should return a string: key=>value key=>value key>value etc...
I do not know how to remove last space at end of result.
EDIT: I cannot use any methods in the String class, and I cannot compare anything to null.
public String toString() {
String result = "";
result+=(this.left.toString());
result+=this.key;
result+="=>";
result+=this.value;
result+=" ";
result+=this.right.toString();
return result;
}
I've tried having a variable for the class that indicates if a NonEmptyTree instance is the largest in the current tree, but console displayed same string.
for example, the string would look like this:
"7=>seven 10=>ten 12=>twelve 15=>fifteen 16=>sixteen 17=>seventeen 20=>twenty 30=>thirty "
any help would be appreciated. thanks
Use String.trim():
return result.trim()
BTW. if you do a lot of String additions it's better to use StringBuilder and its method append() instead of adding multiple Strings with +.
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.left.toString());
result.append(this.key);
result.append("=>");
result.append(this.value);
result.append(" ");
result.append(this.right.toString());
return result.toString().trim();
}
Can you simply add an 'if'? See below:
public String toString()
{
String result = "";
result+=(this.left.toString());
result+=this.key; result+="=>";
result+=this.value;
if (this.right!=null) // Just add this, so it doesn't add an extra space if no right result exists
{
result+=" ";
result+=this.right.toString();
}
return result;
}
Related
Is there a command in java to remove the rest of the string after or before a certain word;
Example:
Remove substring before the word "taken"
before:
"I need this words removed taken please"
after:
"taken please"
String are immutable, you can however find the word and create a substring:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("I need this words removed taken please", "taken");
There is apache-commons-lang class StringUtils that contains exactly you want:
e.g. public static String substringBefore(String str, String separator)
public static String foo(String str, String remove) {
return str.substring(str.indexOf(remove));
}
Clean way to safely remove until a string
String input = "I need this words removed taken please";
String token = "taken";
String result = input.contains(token)
? token + StringUtils.substringAfter(string, token)
: input;
Apache StringUtils functions are null-, empty-, and no match- safe
Since OP provided clear requirements
Remove the rest of the string after or before a certain word
and nobody has fulfilled those yet, here is my approach to the problem. There are certain rules to the implementation, but overall it should satisfy OP's needs, if he or she comes to revisit the question.
public static String remove(String input, String separator, boolean before) {
Objects.requireNonNull(input);
Objects.requireNonNull(separator);
if (input.trim().equals(separator)) {
return separator;
}
if (separator.isEmpty() || input.trim().isEmpty()) {
return input;
}
String[] tokens = input.split(separator);
String target;
if (before) {
target = tokens[0];
} else {
target = tokens[1];
}
return input.replace(target, "");
}
The tester class is:
public class SentenceWithReverseTester
{
public static void main(String[] args)
{
String[] list = new String[]{"aba",
"Madam, I'm Adam",
"nut",
"A man, a plan, a canal, Panama",
"wonderful",
"Go hang a salami, I'm a lasagna hog",
"race car",
"1",
"",
"zero",
"#!:"} ;
for (String line : list) {
SentenceWithReverse sentence = new SentenceWithReverse(line) ;
sentence.reverse() ;
System.out.println(line + " reversed becomes........") ;
System.out.println(sentence.toString()) ;
System.out.println("----------------------------") ;
}
}
}
And for the reverse method I have:
public void reverse()
{
String s = super.toString();
if(s.length() > 0)
{
String first = s.substring(0,1);
String remaining = s.substring(1, s.length());
SentenceWithReverse shorter = new SentenceWithReverse(remaining);
shorter.reverse();
System.out.println(shorter + first);
}
}
I'm not getting the result I want, and I'm not sure what I'm doing wrong here.
You should make reverse() actually return a String, rather than void, so that you can use the result of the reversal. So change void to String in the method's declaration. Then you'll need a couple of return statements inside the method - one for the base case and one for the recursive case.
In the recursive case, the return statement will be something like
return shorter.reverse() + first;
that is, you take the reverse of the shorter sentence, and put the first character back at the end.
In the base case, that is, where the input to the method is "", you can just write
return "";
I'll leave it to you to figure out where to insert these two return statements, within the logic of your method. Good luck.
You're not assigning any member fields in your reverse method. You don't show what fields you have, but I would guess you have a single String field that is returned from toString. You should assign the shorter + first to it where you have the System.out.println call.
I'm working on a special pathfinding system in java, which needs to print it's path at one point. It's far from done but I ran into a problem. When I run my code it instead prints a pointer towards an string rather then the string itself. Here is the code:
public class node {
int optionnum;
node[] options;
String[] dirrections;
String[] route;
boolean[] visited;
public node(){
options= new node[4];
dirrections= new String[4];
route= new String[50];
for (int i=0;i<50;i++){
route[i]="";
}
visited= new boolean[50];
}
public void revmdp(int num){
visited[num]=true;
for(int i=0;i<optionnum;i++){
System.out.println(options[i].route[0]); //how can this be a pointer?
options[i].revmdp(dirrections[i],num);
}
public void revmdp(String nroute, int num){
//System.out.println(route[0]+dirrections[0]);
if (!visited[num]||nroute.length()<route[num].length()){
route[num]=nroute;
visited[num]=true;
for(int i=0;i<optionnum;i++){
options[i].revmdp(route+dirrections[i],num);
}
}
}
}
output looks like this
[Ljava.lang.String;#2d66a22b3;
As you can see in the constructor of path I already set the path towards the string "" (empty string). As the string is not yet changed any futher at moment this code is called I would expect it to return "" however it instead gives these weird string pointers. Anybody know what's up?
Note I have already tried to call route[0][0] but java won't allow that.
Update 3: I found it.
options[i].revmdp(route+dirrections[i],num);
Here you are doing string concatenation on an array and a String. This causes to set route[num] in the level of recursion to this concat result.
Each Java class inerhits from the class Object, which implements the default toString() method. The Source code of the default toString() Method looks like :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
If you do not override the default toString() method, the method above is called.
This is a problem from the CodingBat website. I am pasting the problem first and discussing my efforts after that:
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"
This is what I wrote so far:
public String withoutString(String base, String remove) {
int len_b=base.length();
int len_r = remove.length();
String result="";
if(len_b<1 || len_r<1)
return "";
for (int i =0;i<=len_b-len_r;i++)
{
if(base.substring(i,i+len_r).equals(remove))
{
i=i+len_r-1;
}
else
{
result=result+base.substring(i,i+1);
}
}
if(!(base.substring(len_b-len_r+1, len_b).equals(remove)))
result=result+base.substring(len_b-len_r+1, len_b);
return result;
}
This passes all the test cases except for the ones where the removal of the string should be case-insensitive.
For example: withoutString("This is a FISH", "IS") → "Th a FH"
My code gives me "This is a FH" as I haven't handled case sensitivity in my code. I know that with Regex this could be done in one line. I am more interested in knowing if there is a way to handle these kinds of test cases in my present code.
Also, please let me know if my code could be made more efficient/elegant.
String has an equalsIgnoreCase(String s) method.
you can change this statement base.substring(i,i+len_r).equals(remove) to base.substring(i,i+len_r).equalsIgnoreCase(remove) using equalsIgnoreCase method.
hope helpful.
public String withoutString(String base, String remove)
{
String str=base;
String str1=remove;
String str3=str;
int k=str1.length();
for(int i=0;i<(str.length()-k+1);i++)
{
if(str1.equalsIgnoreCase(str.substring(i, i+k)))
{
String str4=str.substring(i, i+k);
str3=str3.replaceFirst(str4,"" );
}
}
return str3;
}
I did it without any looping :) I suppose it is not the best answer, but it works though
public String withoutString(String base, String remove) {
String lastString = base.replace(remove, "");
remove = remove.toLowerCase();
String veryLastString = lastString.replace(remove, "");
remove = remove.toUpperCase();
String veryVeryLastString = veryLastString.replace(remove, "");
return veryVeryLastString;
}
public String withoutString(String base, String remove) {
String b=base.toLowerCase();
String r=remove.toLowerCase();
if(b.length()<r.length()) return base;
if(b.contains(r)) b=b.replaceAll(r,"");
String temp="";
int j=0;
for(int i=0;i<base.length();i++)
if(j<b.length()){
if(base.substring(i,i+1).equalsIgnoreCase(b.substring(j,j+1))){
temp+=base.substring(i,i+1);
j++;
}
}
return temp;
}
How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?
Eg:
StringBuilder _sb = new StringBuilder("Sam");
I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".
String _s = "Jam";
I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".
How to achieve this?
The first case is done using the insert() method:
_sb.insert(0, "Hello ");
The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:
String s2 = "Hello " + _s;
Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).
However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.
When you write:
String s = "Jam";
s = "Hello " + s;
you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.
1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.
Sure, use StringBuilder.insert():
_sb.insert(0, _s);
You can add a string at the front of an already existing one. for example, if I have a name string name, I can add another string name2 by using:
name = name2 + name;
Don't know if this is helpful or not, but it works. No need to use a string builder.
private static void appendZeroAtStart() {
String strObj = "11";
int maxLegth = 5;
StringBuilder sb = new StringBuilder(strObj);
if (sb.length() <= maxLegth) {
while (sb.length() < maxLegth) {
sb.insert(0, '0');
}
} else {
System.out.println("error");
}
System.out.println("result: " + sb);
}
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
It is better if you find quotation marks by using the indexof() method and then add a string behind that index.
string s="hai";
int s=s.indexof(""");