I am solving the following question: Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
My code is as follows:
public String startWord(String str, String word) {
String front = "";
if (str.length()>=1 && word.length() == 1) {
front = Character.toString(str.charAt(0));
} else {
if (str.length() >= 1 && str.substring(1, word.length() - 1).equals(word.substring(1)))
front = str.substring(0, word.length());
}
return front;
}
front=str.substring(0,word.length()) is returning "" value. It is a logic question, not a coding question. Trying to work on my logic as an amateur programmer. Thanks for bearing me SO!
public String startWord(String str, String word) {
if (str.substring(1, word.length()).equals(word.substring(1, word.length()))) {
return str.substring(0, word.length);
} else {
return "";
}
}
Related
I have two strings to compare
String st1 = "database-2.0/version\"25-00\"";
String st2 = "database2.0version25";
I want to determine if st1 contains st2. In the example provided I expect to get Yes as answer because the order of characters in st2 is same is st1 and it only missing some characters. Is any function in Java library to do such comparison? I am aware of st1.indexOf(st2) and st1.contains(st2) but they didn't work in this case, both returned false.
Try this:
String regex = st2.chars()
.mapToObj(i -> String.valueOf((char) i))
.map(str -> ".*+?^${}()|[]\\".contains(str) ? "\\" + str : str)
.collect(Collectors.joining(".*", ".*", ".*"));
boolean contains = st1.matches(regex);
Here's a rundown:
Get a regex string of the shorter string (st2 in our case - hardcoded - you can automate this of-course), adding .* in front and back, and between each character. (.* matches 0 or more of any character).
String.chars() returns an IntStream, convert it to String with type cast
As #Robert suggested, escape special characters with a backslash.
Check of the longer string matches, which effectivelly means it contains all characters of the short string, and maybe more.
What you are looking for is a subsequence, not a substring.
Here's a working solution I found on geeksforgeeks:
// Recursive Java program to check if a string
// is subsequence of another string
import java.io.*;
class SubSequence
{
// Returns true if str1[] is a subsequence of str2[]
// m is length of str1 and n is length of str2
static boolean isSubSequence(String str1, String str2, int m, int n)
{
// Base Cases
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings are matching
if (str1.charAt(m-1) == str2.charAt(n-1))
return isSubSequence(str1, str2, m-1, n-1);
// If last characters are not matching
return isSubSequence(str1, str2, m, n-1);
}
// Driver program
public static void main (String[] args)
{
String str1 = "database2.0version25";
String str2 = "database2.0/version\"2-00\"";
int m = str1.length();
int n = str2.length();
boolean res = isSubSequence(str1, str2, m, n);
if(res)
System.out.println("Yes");
else
System.out.println("No");
}
}
// Contributed by Pramod Kumar
You can find the subsequence needle in the string haystack by looking for needle's characters in order, starting from an index searchFrom that you update as you find each successive character.
In the following code, note that haystack.indexOf(needleChar, searchFrom) returns the index of the first occurrence of needleChar starting from index searchFrom in haystack.
boolean contains(String haystack, String needle) {
int searchFrom = 0;
for (char needleChar : needle.toCharArray()) {
searchFrom = haystack.indexOf(needleChar, searchFrom);
if (searchFrom == -1) {
return false;
}
}
return true;
}
Still really new to programming and am using some exercises to understand the basics. This is my assignment:
Given a string, return a string made of the first 2 chars (if present), however include first char only if it is 'o' and include the
second only if it is 'z', so "ozymandias" yields "oz".
startOz("ozymandias") → "oz" startOz("bzoo") → "z" startOz("oxx") →
"o"
I already had a look at the solution a do understand it, but can't figure out why my own attempt using substring instead of 'charAt generates a different output. Why does my own code1 using substring give a different output then when I would use 'charAt? Code1 is my own attempt, code2 is the given solution. In the attachments you will find the two outputs. Thank you!
//code 1 own attempt
public String startOz(String str) {
String answer = "";
if ( str.length() >= 1 && str.substring( 0 ).equals("o")) {
answer = answer + str.substring(0);
}
if ( str.length() >= 2 && str.substring( 1 ).equals("z")) {
answer = answer + str.substring(1);
}
return answer;
}
output code1
//code 2 the solution
public String startOz(String str) {
String answer = "";
if ( str.length() >= 1 && str.charAt( 0 ) == 'o') {
answer = answer + str.charAt(0);
}
if ( str.length() >= 2 && str.charAt( 1 ) == 'z') {
answer = answer + str.charAt(1);
}
return answer;
}
output code2
Here is documentation for substring(int index)
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
So for first if you get ozymandias and it is not equal to o.
Correct would be to use:
substring(int beginIndex, int endIndex)
Documentation:
public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Link: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int%29
Read the javadocs on String#substring - you need to add an extra parameter specifying the end of the substring, else it returns the rest of the string.
Learning java as my first language and I found a solution for the problem at codingbat but I don't understand why my solution doesn't work and would love your help.
Given a string of any length, return a new string where the last 2
chars, if present, are swapped, so "coding" yields "codign".
lastTwo("coding") → "codign" lastTwo("cat") → "cta"
lastTwo("ab") → "ba"
This is my not working code:
public String lastTwo(String str) {
int strLength = str.length();
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
if(strLength<2)
return str;
return str.substring(0, strLength-2)+last+bLast;
}
This are the errors and I cant figure out why:
lastTwo("a")
→"Exception:java.lang.StringIndexOutOfBoundsException: String
index out of range: -1 (line number:5)" lastTwo("")
→"Exception:java.lang.StringIndexOutOfBoundsException: String
index out of range: -1 (line number:4)"
It seems there is a problem when input is less than 2 chars but I can't figure out why. To me, the if logic looks okay.
You need to move if condition up in the method as:
public static void main(String[] args) {
System.out.println(lastTwo("coding"));
System.out.println(lastTwo("cat"));
System.out.println(lastTwo("ab"));
System.out.println(lastTwo("a"));
}
public static String lastTwo(String str) {
int strLength = str.length();
if(strLength<2)
return str;
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
return str.substring(0, strLength-2)+last+bLast;
}
This will print:
codign
cta
ba
a
In the method if length of str is less than 2 (e.g. 1) in that case it will be returned else it will compute last and blast and then perform the operation.
When the input is is 1 char, strLength-2 is -1. The methodsubstring throws the error because such index doesn't exist. (The same applies to 0 char and strLength-1)
You have to put this verification on top
if(strLength<2)
return str;
When you have this code, if the string is "", it is trying to get the substring between positions -1,0 and -2,-1. You can't get the substring in a position lower than 0.
int strLength = str.length();
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
One of the overloads for substring can take the starting index , it figures out the last index. So the following should give you the last two chars:
str.substring(java.lang.Math.max(0,str.length()-2))
public String lastTwo(String str) {
if(str != null ) {
int strLength = str.length();
if (strLength < 2)
return str;
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
return str.substring(0, strLength-2)+last+bLast;
}
return null;
}
Problem in your code is String bLast = str.substring(strLength-2,strLength-1);
when strLength = 1 and you subtract by 2 and your index will be -1, hence IndexOutOfboundException occure.
Use above code your problem solved.
Simpler solution is to take the start-of-string and
append the last-char and then
append the before-last-char:
public static String lastTwo(String str) {
if (str.length()<2){
return str;
} else{
return str.substring(0, str.length() - 2) +
str.charAt(str.length() - 1) +
str.charAt(str.length() - 2);
}
}
My task is to use substring to pull out the first few letters of a string if it matches another given string. Basically, given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
The problem with my method is when str is just one letter and word is something else that doesn't match str, I run into a
StringOutOfBound Exception
For example, if str is "h" and word is "ix", it should return nothing. Instead, my method crashes with the stringoutofbound exception. What can I do to fix my logic.
public String startWord(String str, String word) {
int length;
length = word.length();
if (str.substring(0, length).equals(word))
return str.substring(0, length);
else if (str.substring(1, length).equals(word.substring(1, word.length())))
return str.substring(0, length);
else
return "";
}
Correct your conditions this way:
if (str.substring(0, Math.min(length, str.length())).equals(word))
return str.substring(0, length);
else if (str.substring(1, Math.min(length, str.length())).equals(word.substring(1, word.length()))) {
return str.substring(0, length);
}
else
return "";
The reason for the error is that str length is smaller than word length. Please put a check before your logic: if(str.length()<=word.length()).
In the else part, always return "", as it will never satisfy your condition.
if(str.length()>=word.length())
{
if (str.substring(0, length).equals(word))
return str.substring(0, length);
else if (str.substring(1, length).equals(word.substring(1, word.length())))
return str.substring(0, length);
else
return "";
}
else{
return "";
}
I was going through practice questions on CodingBat and I came across this one. It said:
"Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1. "
So far this is the solution I came up with. It works for the most part, however I get one error shown below:
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:3)
This occurs for the case -->> startWord("", "i"). How could this error be fixed?
public String startWord(String str, String word) {
String first = str.substring(1, str.length());
String second = word.substring(1, word.length());
if (str.length() == 0) {
return "";
}
if (str.startsWith(word)) {
return str.substring(0, word.length());
}
else if (first.startsWith(second)) {
return str.substring(0, word.length());
}
return "";
}
You should place your
if (str.length() == 0) {
return "";
}
as a first statement your function, so that the zero length string don't throw the exception.