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.
Related
Say I have the following string:
String string = "122045b5423";
In Java, what would be the most efficient way in finding the last 2 before the b?
I know I can split the string and then use lastIndexOf() method from String class, but
is there a more efficient way with less creating of variables. Can there be a method in the StringBuilder class that will allow us to do this?
If you are looking for a more compact solution, how about regex?
// A 2, followed by arbitrary chars that are not a 2 and finally a b
Pattern pattern = Pattern.compile("(2)[^2]*b");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}
Have not tested it, but something similar should work
I think the simplest (with almost zero memory-overhead) is to simply scan the string yourself:
int findLastCharBeforeChar(final String string, final char anchor, final char needle) {
int i = string.length() - 1;
while (i >= 0 && string.charAt(i) != anchor) {
--i;
}
while (i >= 0) {
if (string.charAt(i) == needle) return i;
--i;
}
return i;
}
If you want to make that a bit shorter (but likely minimally slower and definitely harder to read):
int findLastCharBeforeChar(final String string, final char anchor, final char needle) {
char target = anchor;
while (i >= 0) {
final char ch = string.charAt(i);
if (ch == target) target = needle;
if (target == needle && ch == target) return i;
--i;
}
return i;
}
Not what was asked (most efficient), but followed up in the comments for the "shortest" solution, there you go (note that this is far from efficient, and depending on where you call it, this could be bad):
string.split('b')[0].lastIndexOf('2');
You didn't specify in your OP what should happen if 'b' is not part of the input string. Should the result be -1? (will be with my first implementation) or should the method then just return the index of the last '2' in the string (the string split solution)? Changing the method to handle this case as well is trivial, just check if the first loop terminated at -1 and reset the index to the string's last index.
But this is somewhat moot. You put the 9 lines of code in a method, write proper unit tests for it and then call your new method. Calling the new method is: a) a one-liner b) efficient c) likely to be inlined by the JVM
Look at the method substring of String class (or subSequence). That should give you what you need.
the code Should be something like this
String result = null;
int index = myString.indexOf("b");
if(index > -1) {
if(index >= 2) {
result = myString.substring(index - 2, index);
} else {
result = myString.substring(0, index);
}
}
I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?
Why not just String substr = word.substring(word.length() - 3)?
Update
Please make sure you check that the String is at least 3 characters long before calling substring():
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
// whatever is appropriate in this case
throw new IllegalArgumentException("word has fewer than 3 characters!");
}
I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
You can find more examples under the above link.
Here's some terse code that does the job using regex:
String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
This code returns up to 3; if there are less than 3 it just returns the string.
This is how to do it safely without regex in one line:
String last3 = str == null || str.length() < 3 ?
str : str.substring(str.length() - 3);
By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").
The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:
String last3;
if (str == null || str.length() < 3) {
last3 = str;
} else {
last3 = str.substring(str.length() - 3);
}
String newString = originalString.substring(originalString.length()-3);
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
If you want the String composed of the last three characters, you can use substring(int):
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}
This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow
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 "";
}
}
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);
}
}
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.