I have a method here that searches and prints what i think is all letter combinations of a dictionary in trie form the node entered.
I want to specify each print out and and it to my search(string x) method that finds if a word is in the dictionary.
I can't work out how to specify each letter combination as a string. I am printing them out on a line but don't know how to make that line of print a string to pass into the search method.
public void print(Node node) {
if(node == null) return;
for(int i = 0; i < R; i++) {
if(node.next[i] != null) {
//printing each character
System.out.print((char) (97 + i));
//identifying letter combo
if(node.next[i].isWord == true) {
//here i want to make that combo a string
System.out.println();
}
print(node.next[i]);
}
}
}
You can use
String s1 = "";
s1 = s1 + (char)(97+i); to append characters to a string. You can pass this to your search function
Something, this way,
Initialise the string to "" outside the for loop String s1 = ""
While looping keep adding the characters to the String to maintain a string
s1 = s1 + (char)(97+i);
Now,
if(node.next[i].isWord == true)
{
//u can use the String here;
System.out.println(s1);
}
Related
I'm having some problem with a simple program I'm working on, I just need to ask the user if he wants the regular price or the sale price. And he needs to respond in a string value. Now I know that I just have to use if(price.equals("sale") == true). But the problem comes if I want the user to type something that has spaces in the words, example: if(price.equals("regular price") == true) when I the user types in "regular price" I don't get a response I wanted.
I'm also learning Java by the way.
You can determine if a string contains a word like this:
if (price.toLowerCase().contains("regular"))
If you want to get fancy, you can use regex to match a whole word (eg not "irregular"):
if (price.matches("(?i).*\\bregular\\b.*"))
java equals() method/function works perfectly with the spaces too. Also you don't need to compare the result with true/false. If two string is equal then equals() will automatically return true else it will return false.
public class MyClass {
public static void main(String args[]) {
String a = "A B C";
if(a.equals("A B C")){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
I tested the following program and it returned true while the string has spaces in it.
You want to compare strings with spaces right?
Then you can first compare their lengths, then
If string contains space split it by it, again compare lengths, next check every string.
If it not contains space, just use equals once, here what i come up with:
class cmp {
public static void main(String[] args) {
String s = "test some";
String s2 = "test some";
String s3 = "test not";
String s4 = "testxsome";
System.out.println(cmpStr(s,s2)); // True
System.out.println(cmpStr(s,s3)); // False
System.out.println(cmpStr(s,s4)); // False
}
public static boolean cmpStr(String str1, String str2) {
if (str1.length() != str2.length()) {
System.out.println("Length mismatch.");
return false;
}
if (str1.contains(" ") || str2.contains(" ")) {
String[] a1 = str1.split(" ");
String[] a2 = str2.split(" ");
if (a1.length != a2.length) {
System.out.println("Split Length mismatch.");
return false;
}
for (int i = 0; i < a1.length; i++) {
if (!a1[i].equals(a2[i])) {
System.out.println("One of split mismatch." + a1[i] + " " + a2[i] );
return false;
}
}
} else {
if (!str1.equals(str2)) {
System.out.println("Regular equals returns false.");
return false;
}
}
return true;
}
}
Here I see three methods
Remove all the spaces and hidden characters from the string and check
String input = "regular price";
input = input.replaceAll("\\s+","");
if(price.equals(input))
{
//your code here
}
Check whether the word contains keywords
if (price.toLowerCase().contains("regular"))
Create a regular expression to match your words
I have the following two DNA strings "AACAGTTACC" and "TA-AGGT-CA", I would like to print a corresponding string of numbers, where two elements of two strings indicate a match (0), two elements indicate a mismatch (1) and one element indicates a gap (2).
For example the above two string would produce “10220010201”
I tried a loop through one of the string and check if string.charAt(i).contains("-") but it does not work.
String numbers = "";
for(int k = 0; k<adnX.length();k++) {
// I would like to append numbers to the numbers string
StdOut.printf("%s %s\n", adnX.charAt(k),adnY.charAt(k));
}
Two methods are presented here:
the main method and an auxiliary method.
The auxiliary checks if a given character is a valid DNA character.
The main method has two main parts.
Firstly, it initialises s1 and s2 with the required DNA strings and creates s3 which is an empty string. s3 will be used to store the corresponding numbers in case of a match, miss-match or gap. It assumes that both s1 and s2 have the same length.
In the first part it checks if the character at i-th position in s1 and s2 is a valid DNA character, if it's not it appends a 2 to s3.
In the second part (i.e., of the if statement, the else), it checks if the character at i-th position in s1 is the same as character at i-th position in s2. If it is then it appends a 0, otherwise it appends a 1.
The result is printed at the end.
public class DNACheck {
public static boolean isDNA(char c) {
String dna = "ATGC";
boolean inSequence = false;
for (int i = 0; i < dna.length() && !inSequence;i++) {
if (dna.charAt(i) == c) inSequence = true;
}
return inSequence;
}
public static void main(String[] args) {
String s1 = "AACAGTTACC";
String s2 = "TA-AGGT-CA";
String s3 = "";
for(int k = 0;k< s1.length();k++) {
// I would like to append numbers to the numbers string
if (!isDNA(s1.charAt(k)) || !isDNA(s2.charAt(k))) {
s3 = s3 + '2';
}
else {
if (s1.charAt(k) == s2.charAt(k)) {
s3 = s3 + '0';
}
else {
s3 = s3 + '1';
}
}
}
System.out.println(s3);
}
}
Assuming that inputs always have the same length and two gaps should result in a match:
String adnX = "AACAGTTACC";
String adnY = "TA-AGGT-CA";
StringBuilder numbers = new StringBuilder();
for (int i = 0; i < adnX.length(); i++) {
if (adnX.charAt(i) == adnY.charAt(i)) {
numbers.append(0);
} else if (adnX.charAt(i) == '-' || adnY.charAt(i) == '-') {
numbers.append(2);
} else {
numbers.append(1);
}
}
System.out.println(adnX);
System.out.println(adnY);
System.out.println(numbers);
Will output:
AACAGTTACC
TA-AGGT-CA
1020010201
How to remove Consecutive Characters at each Iteration..
Below is the screenshot that explains the question with more details
MySolution
Initially I checked whether there are any Consecutive characters.
If yes,Then,remove all the consecutive characters and when there are no consecutive characters add the remaining characters to another String.
If no Consecutive Characters just simply increment it.
public static void print(){
String s1="aabcccdee"; I have taken a sample test case
String s2="";
for(int i=0;i<s1.length();){
if(s1.charAt(i)==s1.charAt(i+1)){
while(s1.charAt(i)==s1.charAt(i+1)){
i++;
}
for(int j=i+1;j<s1.length();j++){
s2=s2+s1.charAt(j);
}
s1=s2;
}
else
i++;
}
System.out.println(s1);
}
Output Shown
An infinite Loop
Expected Output for the give sample is
bd
Can Anyone guide me how to correct?
You can simply use String::replaceFirts with this regex (.)\1+ which means matche any charater (.) which followed by itself \1 one or more time + with empty.
In case you want to replace first by first you have to check the input, if after each iteration still contain more than one consecutive characters or not, in this case you can use Pattern and Matcher like this :
String[] strings = {"aabcccdee", "abbabba", "abbd "};
for (String str : strings) {
Pattern pattern = Pattern.compile("([a-z])\\1");
// While the input contain more than one consecutive char make a replace
while (pattern.matcher(str).find()) {
// Note : use replaceFirst instead of replaceAll
str = str.replaceFirst("(.)\\1+", "");
}
System.out.println(str);
}
Outputs
aabcccdee -> bd
abbabba -> a
abbd -> ad
Update
I had misread the question. The intent is to also remove the consecutive characters after each replacement. The below code does that.
private static String removeDoubles(String str) {
int s = -1;
for (int i = 1; i < str.length(); i++) {
// If the current character is the same as the previous one,
// remember its start position, but only if it is not set yet
// (its value is -1)
if (str.charAt(i) == str.charAt(i - 1)) {
if (s == -1) {
s = i - 1;
}
}
else if (s != -1) {
// If the current char is not equal to the previous one,
// we have found our end position. Cut the characters away
// from the string.
str = str.substring(0, s) + str.substring(i);
// Reset i. Notice that we don't have to loop from 0 on,
// instead we can start from our last replacement position.
i = s - 1;
// Finally reset our start position
s = -1;
}
}
if (s != -1) {
// Check the last portion
str = str.substring(0, s);
}
return str;
}
Note that this is almost 10 times faster than YCF_L's answer.
Original post
You are almost there, but you don't have to use multiple for loops. You just need one loop, because whether to remove characters from the string only depends on subsequent characters; we don't need to count anything.
Try this:
private static String removeDoubles(String s) {
boolean rem = false;
String n = "";
for (int i = 0; i < s.length() - 1; i++) {
// First, if the current char equals the next char, don't add the
// character to the new string and set 'rem' to true, which is used
// to remove the last character of the sequence of the same
// characters.
if (s.charAt(i) == s.charAt(i + 1)) {
rem = true;
}
// If this is the last character of a sequence of 'doubles', then
// reset 'rem' to false.
else if (rem) {
rem = false;
}
// Else add the current character to the new string
else {
n += s.charAt(i);
}
}
// We haven't checked the last character yet. Let's add it to the string
// if 'rem' is false.
if (!rem) {
n += s.charAt(s.length() - 1);
}
return n;
}
Note that this code is on average more than three times faster than regular expressions.
Try something like this:
public static void print() {
String s1 = "abcccbd"; // I have taken a sample test case
String s2 = "";
while (!s1.equals(s2)) {
s2 = s1;
s1 = s1.replaceAll("(.)\\1+", "");
}
System.out.println(s1);
}
consider this easier to understand code
String s1="aabcccdee";
while (true) {
rvpoint:
for (int x = 0; x < s1.length() -1; x++)
{
char c = s1.charAt(x);
if (c == s1.charAt(x+ 1)) {
s1 = s1.replace(String.valueOf(c), "");
continue rvpoint; // keep looping if a replacement was made
}
}
break; // break out of outer loop, if replacement not found
}
System.out.println(s1);
note
This will only work for the first iteration, put into a method and keep calling until the sizes do not change
I have a strings that contain only digits. String itself would look like this "0011112222111000" or "1111111000". I'd like to know how can I get an array of substrings which will consist of strings with only one digit.
For example, if I have "00011111122233322211111111110000000" string, I 'd like it to be in string array(string[]) which contains ["000","111111","222","333","222","1111111111","0000000"].
This is what I've tried
for (int i = (innerHierarchy.length()-1); i >= 1; i--) {
Log.e("Point_1", "innerHierarchy " + innerHierarchy.charAt(i));
c = Character.toChars(48 + max);
Log.e("Point_1", "c " + c[0]);
if (innerHierarchy.charAt(i) < c[0] && innerHierarchy.charAt(i - 1) == c[0]) {
Log.e("Point_1", "Start " + string.charAt(i));
o = i;
} else if (innerHierarchy.charAt(i) == c[0] && innerHierarchy.charAt(i - 1) < c[0]) {
Log.e("Point_1", "End " + string.charAt(i));
o1 = i;
string[j] = string.substring(o1,o);
j=j+1;
}
}
But this code won't work if string looks like this "111111000"
Thank you.
I have "00011111122233322211111111110000000" string, I 'd like it to
be in string array(string[]) which contains
["000","111111","222","333","222","1111111111","0000000"]
One approach I can think of right now (O(n)) (might not be the most efficient but would solve your problem) would be traversing the string of numbers i.e. ("00011111122233322211111111110000000" in your case )
and if char at that position under consideration is not same as char at previous position then making string till that part as one string and continuing.
(approach)
considering str= "00011111122233322211111111110000000"
//starting from position 1 (ie from 2nd char which is '0')
//which is same as prev character ( i.e 1st char which is '0')
// continue in traversal
// now char at pos 2 which is again '0'
// keep traversing
// but then char at position 3 is 1
// so stop here and
//make substring till here-1 as one string
//so "000" came as one string
//continue in same manner.
code
import java.util.*;
public class A {
public static void main(String []args){
String str = "00011111122233322211111111110000000";
str+='-'; //appended '-' to get last 0000000 as well into answer
//otherwise it misses last string which i guess was your problem
String one_element ="";
int start=0;
for(int i=1;i<str.length();i++){
if(str.charAt(i)== str.charAt(i-1) )
{
}
else{
one_element = str.substring(start,i);
start = i;
System.out.println(one_element);//add one_element into ArrayList if required.
}
}
}
}
I have printed each element here as string , if you need an array of all those you can simply use an array_list and keep adding one_element in array_list instead of printing.
I know I'm missing some things and that's what I really need help with. The code doesn't work in all cases and am looking for help improving/fixing it.
Assignment:
The code I have so far:
public String word(int num, String words)
{
int l = words.indexOf(" ");
int r = words.indexOf(" ", l+1);
for(int i = 3; i <= num; i++){
l = r;
r = words.indexOf(" ", l+1);
//if(i != num)
// l = r;
}
String theword = words.substring(l,r);
return theword;
}
}
As this is clearly homework, I will give you text only.
Your approach may work eventually, but it is laborious and overly complicated, so it's hard to debug and hard to get right.
make use of String's API by using the split() method
after splitting the sentence into an array of word Strings, return the element at num less one (array are indexed starting at zero
check the length of the array first, in case there are less words than num, and take whatever action you think is appropriate in that case
For part 2, a solution in a simple form may be:
create a new blank string for the result
iterate over the characters of the given string adding the character to the front of the result string
make use of String's toUpperCase() method
Since this is homework and you have showed some effort. This is how you can do part 1 of your question. This code is pretty evident.
1) I am returning null if number is greater than the number of words in string as we dont want user to enter 5 when there are only 2 words in a string
2) Splitting the string by space and basically returning the array with the number mentioned by user
There are more conditions which you must figure out such as telling the user to enter a number of the string length since it would not give him any result and taking input from Scanner instead of directy adding input in method.
public static String word(int num, String words)
{
String wordsArr[] = words.split(" ");
if(num <= 0 || num > wordsArr.length) return null;
return (wordsArr[num-1]);
}
the second part of your question must be attempted by you.
Well... not often you see people coming here with homework AND showing effort at the same time so bravo :).
This is example of how you can split the string and return the [x] element from that string
public class SO {
public static void main(String[] args) throws Exception {
int number = 3;
String word = "Hello this is sample code";
SO words = new SO();
words.returnWord(number, word);
}
private void returnWord(int number, String word) throws Exception {
String[] words = word.split("\\s+");
int numberOfWords = words.length;
if(numberOfWords >= number) {
System.out.println(words[number-1]);
} else {
throw new Exception("Not enought words!!!");
}
}
}
Yes it is a working example but do not just copy and paste that for your homework - as simple question from teacher - What is this doing, or how this works and your out :)! So understand the code, and try to modify it in a way that you are familiar what is doing what. Also its worth getting some Java book - and i recommend Head first Java by O'Really <- v.good beginner book!
if you have any questions please do ask!. Note that this answer is not 100% with what the textbook is asking for, so you can modify this code accordingly.
As of part 2. Well what Bohemian said will also do, but there is a lot quicker solution to this.
Look at StringBuilder(); there is a method on it that will be of your interest.
To convert String so all letter are upper case you can use .toUpperCase() method on this reversed string :)
You can try:
public class trial {
public static void main(String[] args)
{
System.out.println(specificword(0, "yours faithfully kyobe"));
System.out.println(reverseString("derrick"));}
public static String specificword(int number, String word){
//split by space
String [] parts = word.split("\\ ");
if(number <= parts.length){
return parts[number];
}
else{
return "null String";
}
}
public static String reverseString(String n){
String c ="";
for(int i = n.length()-1; i>=0; i--){
char m = n.charAt(i);
c = c + m;
}
String m = c.toUpperCase();
return m;
}
}
For the first problem, I'll give you two approaches (1. is recommended):
Use the String.split method to split the words up into an array of words, where each element is a word. Instead of one string containing all of the words, such as "hello my name is Michael", it will create an array of the words, like so [hello, my, name, is, Michael] and that way you can use the array to access the words. Very easy:
public static String word(int num, String words)
{
// split words string into array by the spaces
String[] wordArray = words.split(" "); // or = words.split("\\s+");
// if the number is within the range
if (num > 0 && num <= wordArray.length) {
return wordArray[num - 1]; // return the word from the word array
} else { // the number is not within the range of words
return null;
}
}
Only use this if you cannot use arrays! Loop through the word until you have found enough spaces to match the word you want to find:
public static String word(int num, String words)
{
for (int i = 0; i < words.length(); i++) { // every character in words
if (words.substring(i, i+1).equals(" ")) { // if word is a space
num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
}
if (num == 1) { // found all words
// return this word
int lastIndex = i+1;
while (lastIndex < words.length()) { // until end of words string
if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
break;
}
lastIndex = lastIndex + 1; // not a space so keep moving along the word
}
/*
// or you could use this to find the last index:
int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
if (lastIndex == -1) { // couldn't find another space
lastIndex = words.length(); // so just make it the last letter in words
}*/
if (words.substring(i, i+1).equals(" ")) { // not the first word
return words.substring(i+1, lastIndex);
} else {
return words.substring(i, lastIndex);
}
}
}
return null; // didn't find word
}
As for the second problem, just iterate backwards through the string and add each letter to a new string. You add each letter from the original string to a new string, but just back to front. And you can use String.toUpperCase() to convert the string to upper case. Something like this:
public static String reverse(String str) {
String reversedString = ""; // this will be the reversed string
// for every character started at the END of the string
for (int i = str.length() - 1; i > -1; i--) {
// add it to the reverse string
reversedString += str.substring(i, i+1);
}
return reversedString.toUpperCase(); // return it in upper case
}