How to separate a string into substrings of two characters - java

I am trying to split strings in substrings of two chararters for example for the input: "ABCDE" i want to get the substrings "AB" "BC" "CD" "DE".
I tried with this:
String route = "ABCDE";
int i = 0;
while(i < route.length()) {
String sub = route.substring(i,i+2);
System.out.println(sub);
i++;
}
but the index (i) gets out of range int the last iteration and causes an error.
is there any way to do this without getting the index (i) out of range ?

You need to change the loop condition.
while(i < route.length()-1)
In your code i goes till (length-1) and than in the substring(i,i+2) function you gives end index i+2. It is higher than largest index of string.
Also, As far as I know calling a library function in a loop condition is not considered a good practice.
In each iteration you call this function which is time consuming.
control goes to that subroutine in each iteration.
A good alternative to this would be to store the length in a variable and use that in a condition.
int temp = route.length()-1;
while(i<temp){

This should work fine
String route = "ABCDE";
if( route.length() > 2){
int i = 0;
do {
String res = route.substring(i,i+2);
System.out.println(res);
i++;
} while (i + 1 < route.length());
}
else{
System.out.println(route);
}
Edit: Added boundary case for the string has length less than 2

Add check for the size of the string to trap the error:
String route = "ABCDE";
int i = 0;
while(i < route.length()) {
if(i < route.length() - 1) {
String sub = route.substring(i,i+2);
System.out.println(sub);
} else {
String sub = route.substring(i,i+1);
System.out.println(sub);
i++;
}
So whenever the i counter almost close to string size, get the last char.

You are getting an StringIndexOutOfBoundsException because you are trying to access an index of the String that doesn't exist.
To fix this, change your loop condition from
while(i < route.length())
to
while(i < route.length() - 1)
Without the -1 on the last iteration of the while loop i + 2 is equal to 71 which is out of the Strings bounds.
Another (cleaner) solution to this problem is a for loop:
for(int i = 0; i < route.length() - 1; i++) {
System.out.println(route.substring(j, j + 2));
}
The for loop in this situation is just shorter as the declaration, conditional, and increment statements are all in one line.
1: This 7 reduces to 6 since the endIndex of substring is exclusive.

As denis already pointed out, the bug in the code is in the loop condition.
Should be: while(i < route.length() - 1)
. However, how about simplifying this logic to use a for loop.
String route = "ABCDE";
for (int i=0; i+2<=route.length(); i++)
System.out.println(route.substring(i,i+2));

you can not use
i < route.length(),because when i = 5, String sub = route.substring(i,i+2); the i+2=7,is out of index,so use i<route.length instead

Related

String out of Index :java.lang.ArrayIndexOutOfBoundsException. String overflows maybe

class Solution {
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;//index of strs
int j;//index of the first one of string
for(j = 0; j < strs[0].length(); j++){
compareElement = strs[0].charAt(j);
for(i = 1; i < strs.length; i++){
if(compareElement == strs[i].charAt(j)){
if(i == strs.length - 1)
result += compareElement;
else
continue;
}
else{
break;
}
}
}
return result;
}
}
Test sample is
Input: ["flower","flow","flight"]
Output: "fl"
hi there I have got a problem with string in Java in my 4th small program in Leetcode. The aim of this function is to find the longest common prefix string amongst an array of strings. But the exception
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:614)
at Solution.longestCommonPrefix(Solution.java:11)
at __DriverSolution__.__helper__(__Driver__.java:4)
appears over again.
Has someone any idea? Thanks!
I think this is where you go wrong:
if(compareElement == strs[i].charAt(j))
j can become too large as it goes from 0 to strs[0].lenght() (see your outer loop).
If strs[i].lengt() is smaller than strs[0].length() you get an StringIndexOutOfBoundsException.
When you iterate through the comparison strings, you're never checking the length of the string you're comparing. In your example the test case flow. The char at index 4 doesn't exist since only indices 0-3 are defined. if(compareElement == strs[i].charAt(j)){ when j is 4 it'll mess up. In order to fix it you have to make sure you're not going past the length of the string. In addition to that look up what a StringBuilder is, for this small of a test case it won't matter however as you go up larger it will.
Your code fails if you have an element in the array which is shorter than the first element. You need to check that j is still smaller than the length of the string you're comparing:
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;// index of strs
int j;// index of the first one of string
for (j = 0; j < strs[0].length(); j++) {
compareElement = strs[0].charAt(j);
for (i = 1; i < strs.length; i++) {
if (j < strs[i].length() && compareElement == strs[i].charAt(j)) {
if (i == strs.length - 1)
result += compareElement;
else
continue;
} else {
break;
}
}
}
return result;
}

StringIndexOutOfBounds in Java

I have two exact copies of code here, except one has '<' in the for loops while the other has '<='. Could someone please explain why I get the index out of bounds exception when I use '<=', but then it works fine with '<'
Error code:
for(int i = 0; i <= str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j <= str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
Working code:
for(int i = 0; i < str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j < str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
If I don't use <= how will it compare the last character in the string?
Valid String indexes in Java, just like the indexes in any array, go from zero to length minus one. So clearly if you set up your condition to go up to i <= str.length(), you'll get outside the string.
Remember that a String on the inside is nothing more than a char[], and again: the valid indexes go from 0 to length-1. This is a convention, followed by many other programming languages that decided to start counting from zero instead of one.
Because you cannot access str.chatAt(str.length()) without throwing a exception.
a < b means "a is less than b" and it will be false when a equals to b.
a <= b means "a is less than or equals to b" and it will be true when a equals to b.
To compare the last character in the string, write some code to do so, compile and run.
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length() returns the number of characters in the String. So "String".length() returns 6.
Now, when using indices, you start with zero. so "String".charAt(0) returns 'S'. "String".charAt(6) gives you a StringIndexOutOfBoundsException because the last character in "String" is at index 5.
String indexes begin at 0. str.length() returns how many elements are in your array. if you have a string
"dog"
"dog".length() = 3,
'd':0, 'o':1, 'g':2.
Since your for loop initializes i to 0, the working loop goes through indexes 0-2, which is 3 values, while the non-working one goes 0-3, and references a null, and str.charAt(3) does not exist.

Using if else in For Loop increment

I have a problem in Java:
Given a string, return a string made of the chars at indexes 0,1,4,5,8,9...
I know how to solve it, however I was wondering if it's possible for me to use if-else in for-loop increment itself, for example:
for (int i=0; i < str.length(); if (i%4==0) i++, else i+=3){
result += str.charAt(i);
}
Can we do something like that?
You can't use an if there but you can use a ternary operator
for (int i = 0; i < str.length(); i += i%4 == 0 ? 1 : 3) {
result += str.charAt(i);
}
Putting it simply, you want two characters from every 4th position starting from 0. You can use the following code for that:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < safeLength; i += 4){
builder.Append(str.substring(i, i + 2));
}
Unlike the answer that you have accepted, in this answer there is:
no obfuscation;
the intent is very clear; and,
most importantly, no if-else or ternary operator.
Update: I'm aware of the possibility of IndexOutOfBoundsException but because I wanted to keep the attention on core logic only, I didn't add that check. Here is the code that needs to be added to avoid the exceptional cases:
Put following code above the for loop:
int safeLength = str.Length();
bool lengthCorrectionWasNeeded = (str.length() - 1) % 4 == 0;
if (lengthCorrectionWasNeeded) safeLength--;
Put following code below the for loop:
if (lengthCorrectionWasNeeded) builder.append(str.substring(str.length() - 2));
At the end builder.ToString() will contain the desired string.
As for the issue "Using if else in For Loop increment", I agree with Manos's answer.
The following are some of my suggestion.
In my opinion, it is important that codes are clear and clean.
And it is a good practice that extract str.length() to a local variable instead of 'calculating' it in every loop.
And if you are building a string by appending it lots of time, StringBuilder is a good choice.
String str = "this is your string ...";
int length = str.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length ; i += (i%4 == 0 ? 1 : 3)){
builder.append(str.charAt(i));
}
String result = builder.toString();

I am having trouble getting substring to work

This method is supposed to get the number of occurrences of a certain pattern and return the int value. I keep getting this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Code
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i <= strand.length(); i++) {
if (strand.substring(i, i + pattern.length()) == pattern) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
i <= strand.length()
.length() returns the total length of the string and the indexes of the string start at 0. So if i is equal to the string length you will get an out of bounds. To fix this use:
i <= strand.length() - 1
or
i < strand.length()
You're iterating too far on your String.
For substring, charAt, or any method that requires to you to use an exact numerical value to get at a character or a group of characters, the size of the String is defined as the result of the length() call minus 1.
It's like an array (since it is backed by a char[]): "cat" has length 3, but it's zero based, so I can only go up to 2.
Change your condition to be strictly less-than, and not less-than or equal to.
StringIndexOutOfBoundsException comes when the index where you are pointing to is null(does not exist). Here the problem I see is in strand.length().
for (int i = 0; i < strand.length(); i++)
This should work fine
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) {
if (strand.substring(i, i + pattern.length()) .equals(pattern)) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
(changed == to .equals. for reason see this post) Use equalIgnoreCase if it is case insensitive.
length() is already described in rest of the answers
== tests for reference equality.
.equals() tests for value equality.
How to compare Strings in java
You need to correct your condition check in loop and also add new check inside loop block:
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) { // Updated check
if((i + pattern.length()) >= strand.length()) // New condition to avoid exception
break;
if (strand.substring(i, i + pattern.length()) == pattern) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
New added check can also be handled in loop condition itself.
i <= strand.length() in your for loop is your problem...
length() returns the number of elements in an Array. Always remember that index starts from 0. So, if length is 5, you have 5 elements 0,1,2,3 and 4. So, you have to use i<strand.length();
You get StringIndexOutOfBoundsException because element with index "length-1" is the last element and you are trying to access element with index="length".
3 problems...
Change <= to < in your loop.
You also need to limit the right side of the substring to not be past the end of the string.
And you need to use .equals() not ==.
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) {
if (strand.substring(i, Math.min(i + pattern.length(), strand.length())).equals(pattern)) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}

Writing a word backwards using only 1 string converted to an array, a character, and an integer

I'm trying to create a code that writes an array backwards and can only use an array, character, and an integer. So far I have this, but it isn't doing anything. I'm a beginner at java.
import javax.swing.JOptionPane;
public class TestingArraysUsingOneArray
{
public static void main(String args[])
{
{
String str = JOptionPane.showInputDialog("Enter any text that you want to reverse.");
char[] charArray = str.toCharArray();
char current;
int a = 0;
for (int i = 0; i>=str.length()%2; i++) {
current = str.charAt(a);
charArray[a] = str.charAt(str.length()-a);
charArray[str.length()-a] = current;
a++;
}
System.out.println(charArray);
}
}
}
The output I'm getting is hello when I enter in hello. What do I need to change to get this program to work?
Your don't need half the code. I would try to make it as simple as possible. Try this
String str = ...
for(int i = str.length() - 1; i >= 0; i--)
System.out.print(str.chatAt(i));
System.out.println();
If the assignment says you have to reverse an array of chars you can do this.
String str = ...
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length/2; i++) {
char ch = chars[i];
chars[i] = chars[chars.length - i - 1];
chars[chars.length - i - 1] = ch;
}
System.out.println(new String(chars));
As you can see this is needlessly complicated, so you would not do this. Another way you can do this if you don't want to use a loop is
String str = ...
System.out.println(new StringBuilder(str).reverse());
Well, for one thing, I think you want i<str.length()/2 - this will give you half the length. If you say i>=str.length()%2, you're getting the remainder when its length is divided by 2 - which is always either 1 or 0, and the loop continues as long as i is more than either 1 or 0. This should result in an infinite loop. Also, you don't need the variable a, as it is always equivalent to i. This, however, results in the string index being out of bounds sometimes, but I'll let you figure out how to solve that.
Your for loop is never entering because it should be i < str.length(), because at the moment when i is 0, the current check will immediately fail.
With that condition set, you need to change the two instances of str.length()-a to str.length()-a-1, because str.length-a when a is 0 will cause an StringIndexOutOfBoundException because the maximum index you can access is str.length-1.
Those are just corrections to the existing code. There's a better, more concise way of reversing the string suggested in another answer, which is the one you should accept.
What you want to do is replace the first character with the last and so on..
char[] charArray = str.toCharArray();
char current;
for (int i = 0; i < charArray.length / 2; i++) {
current = charArray[i];
charArray[i] = charArray[charArray.length - i - 1];
charArray[charArray.length - i - 1] = current;
}
The a int is completely redundant, and it would be a second int in your code - don't forget the variable in the for loop.

Categories