I have found the following program to check if a string is palindrome.
import java.util.Scanner;
public class PalindromeString{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
String s = in.next();
String r = "";
for(int i=s.length()-1; i>=0; i--){
r = r+s.charAt(i);
}
System.out.println("Reverse of entered string "+s+" is "+r);
if(r.equals(s)){
System.out.println("String "+s+" is palindrome.");
}else{
System.out.println("String "+s+" is not palindrome.");
}
}
}
I did not understand why the coder initialized the loop variable i to s.length()-1. Can anyone explain me why? I have searched related content for string length but couldn't find an answer for this.
The indices of elements in Java (and most other languages) will always begin with 0. When considering an array/string the indices of the contained elements will start at 0 and end at (size of array/length of string - 1).
String string = "Hello World"
In the example above we have an array with 11 elements. Therefore the indices range from 0 to 10 (The string length minus one).
"H" is the first element in the string and is therefore indexed '0', i.e. string[0] = "H".
"e" is indexed '1' i.e. string[1] = "e", etc. The last element will be indexed '10' i.e. string[10] = "d".
I think this explains it better than I do (and has pictures!) -- http://codingbat.com/doc/java-string-introduction.html
Read this for more info on manipulating and accessing arrays -- http://tutorials.jenkov.com/java/arrays.html
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10. 应该是这样子的
Because java indexing arrays from 0.
For example "Hello" string's length is 5. the 'H' is the 0. charachter of the "Hello" string.
According to this, the 'e' charachter is int the 1. position, and the 'o' is in the 4.
Easy to see that there are no 5 (the length of the string) position, so if we want the last charachter, we need the length-1. position.
Also I suggest take a look at this
Strings are arrays of chars, and array indexes start to count from 0.
length is the amount of elements in that char array, but because the array starts at 0 the highest index is the amount of elements - 1 ==> .length() -1
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10.
Because Java Strings use zero-based indexing.
i.e. Character indices in the string are from 0...n-1
Related
I have a String of say, length is 5000. I want to find out the number of times the letter 'R' (Case Sensitive) is used. Below are the two passable solution...
Convert to char array, loop it to perform a condition to check and increment a counter.
Use Substring() with the character 'R' to get an array which could fetch a array. So, the total length of the array +1 will be number of times, the 'R' character in the string(This is not a better solution)
Help me out with the efficient solution on the cards for this. Thanks.
try this one
String text = "ABCabcRRRRRrrr";
int count = text.length() - text.replace("R", "").length();
If you're using java >= 8 you can use the Streams:
public static void main(String args[]) {
String str= "abcderfgtretRetRotpabcderfgtretRetRotp"
System.out.println(str.chars().filter(c -> c == 'R').count());
}
String str = //the actual string
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)=='R')
{
capitalRCount++;
}
}
I'm attempting to take in a string from the console of a certain length and set the empty characters in the string to an asterisk.
System.out.println("Enter a string of digits.");
someString = input.next();
if(someString.matches("\\d{0,9}")) {
charArr = someString.toCharArray();
for ( char digit: charArr) {
if(!Character.isDefined(charArr[digit])){
charArr[digit] = '*';
}
}
System.out.printf("Your string is: %s%n", new String(charArr));
This code is throwing an array index out of bounds exception and I'm not sure why.
for ( char digit: charArr) will iterate over each character from charArr.
Thus, digit contains a character value from charArr.
When you access the element from charArr by writing charArr[digit], you are converting digit from datatype char to int value.
For example, you have charArr = new char[]{'a','b','c'}.
charArr['a'] is equivalent to charArr[97] but charArr has size of length 3 only.
Thus, charArr cannot access the element outsize of its size and throws ArrayIndexOutOfBoundsException.
Solution: loop through the array index wise rather than element wise.
for(int i = 0; i < charArr.length; i++) {
// access using charArr[i] instead of charArr[digit]
...
}
Think you could do it in one line with:
newString = someString.replaceAll("\\s", "*");
"\s" is the regex pattern for a whitespace character.
I think you're mixing your for blocks. In your example, you're going over every character in your someString.toCharArray() so you can't do !Character.isDefined(charArr[digit]) because digit is a char, not an int. You can't take the index of an array with a char.
If you're checking purely if a character is a space, you can simply do one of the following:
if (digit != ' ')
if (!Character.isWhiteSpace(digit)
if (Character.isDigit(digit))
This loop statement:
for (char digit: charArr) {
iterates the values in the array. The values have type char and can be anything from 0 to 65535. However, this statement
if (!Character.isDefined(charArr[digit])) {
uses digit as an index for the array. For that to "work" (i.e. not throw an exception), the value needs to be in the range 0 to charArr.length - 1. Clearly, for the input string you are using, some of those values are not acceptable as indexes (e.g. value >= charArr.length) and an exception ensues.
But you don't want to fix that by testing value is in the range required. The values of value are not (from a semantic perspective) array indexes anyway. (If you use them as if they are indexes, you will end up missing some positions in the array.)
If you want to index the values in the array, do this:
for (int i = 0; i < charArr.length; i++) {
and then use i as the index.
Even when you have fixed that, there is still a problem with your code ... for some usecases.
If your input is encoded using UTF-8 (for example) it could include Unicode codepoints (characters) that are greater than 65535, and are encoded in the Java string as two consective char values. (A so-called surrogate pair.) If your string contains surrogate pairs, then isDefined(char) is not a valid test. Instead you should be using isDefined(int) and (more importantly) iterating the Unicode codepoints in the string, not the char values.
I am trying to convert a long to a string and then find a certain number in string based on the Strings index.
I get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at TestFile.main(TestFile.java:12)
Why does this not work? I thought I understood substring but I guess I don't.
Also if I change it to substring((i-2), (i-1)) I get a number that is very different than the long. But I don't get the errors anymore.
import java.util.*;
public class TestFile {
public static void main(String args[]) {
long hello = 22L;
// System.out.println(HW3.sumOfDoubleEvenPlace(hello));
String strLong = Long.toString(hello);
int i = strLong.length();
System.out.println(i);
int temp;
String strLongcut = strLong.substring((i-2), (i-2));
temp = Integer.valueOf(strLongcut.charAt(0));
System.out.println(temp);
}
}
So I just realized that the second part of substring is the length of the part I want to take, not an index.
I still cant get the value of my long returned correctly.
Thanks for your help !
You have an empty string (containing no characters) and you try to get the first character from it. It doesn't have a first character (because it has no characters), so charAt throws an exception.
In substring, the first argument is the index where the substring starts, and the second argument is where it ends. (For example, 2 means "before the character at index 2").
In your code, i contains 2, so i-2 is 0. strLong contains "22".
You call "22".substring(0, 0) which returns the substring starting before the first character (index 0), and ending before the first character.
substring starts here
v
2 2
^
substring ends here
Obviously, this contains no characters, so substring returns the empty string "".
The substring method goes as follows:
myString.substring(indexOfFirstCharacterInTheSubstring,
indexOfLastCharacterInSubstring + 1);
So what you have by making both parameters the same index is creating a substring of length 0, which doesn't even have an index 0 (if did it would be of length >= 1), and thus the error.
I'm new to programming (taking a class) and I'm not sure how to accomplish this one task.
"Ignoring case, find the last occurrence of an ‘a’ in the input and remove all of the characters following it. In the case where there are no ‘a’s in the word, remove all but the first two characters (reminder: do not use if statements or loops). At the end of the now truncated word, add a number that is the percentage that the length of the truncated word is of the length of the original word; this percentage should be rounded to the closest integer value."
I'll be fine with the percentage part, but I'm not sure how to do the first part.
How do I remove only after the last occurrence of 'a'?
If there is no 'a' how do I cut it off after the first two letters without using an if statement?
I'm assuming its to be done using string manipulation and various substrings, but I'm not sure how the criteria for the substrings should be made.
Remember, Java newbie! I don't know a lot of fancy coding techniques yet.
Thank you!
String#toLowerCase - remove all case from the String
String#lastIndexOf will tell you where the last occurrence of the specified String occurs, will return -1 if there is no occurrence, this is important.
String#subString will allow you to generate a new String based on a sub element of the current String
Math#max, Math#min
Given String input, consider the following as a possible starting point:
int indexOfSmallA = input.lastIndexOf('a');
int indexOfBigA = input.lastIndexOf('A');
int beginIndex = Math.max(indexOfSmallA, indexOfBigA);
// if not found, begin at 2 or end of input, else begin after last 'a'
beginIndex = (beginIndex == -1) ? Math.min(2, input.length()) : beginIndex + 1;
String result = input.substring(beginIndex);
For finding the last occurence of 'a' or 'A' you can use...
int index = Math.max(str.lastIndexOf('a'),str.lastIndexOf('A'));
index = (index==-1)?Math.min(2,str.length()):index+1;
Once you get the index you can use the following to remove the characters after it...
str.substring(0,index);
i am working on text. I want to find the number of words after the last occurrence of a particular word in an array of strings.For instance,
String[] array={cat,rat,cat,bat,cat,cat,bat,fat,mat}
and I want to find the last occurrence of every word in this array and the number of words after the last occurrence .
How can I do it???
Iterate and count the array backwards and every new word that you encounter this way is the last or only instance of this word in the array. You can i.e. put the words in a hash set to check whether you have seen them already. Whenever you detect a new word this way you get the number of words behind it from the counter or by calculating array.length - currentPosition.
There is a solution with RegEx in DotNet if you will work with strings.
To search in an array here is an short example:
using System;
class Program
{
static void Main()
{
//
// Use this array of string references.
//
string[] array1 = { "cat", "dog", "carrot", "bird" };
//
// Find first element starting with substring.
//
string value1 = Array.Find(array1,
element => element.StartsWith("car", StringComparison.Ordinal));
//
// Find first element of three characters length.
//
string value2 = Array.Find(array1,
element => element.Length == 3);
//
// Find all elements not greater than four letters long.
//
string[] array2 = Array.FindAll(array1,
element => element.Length <= 4);
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(string.Join(",", array2));
}
}
Also you can take a look to MSDN Example
Hope that helps
Regards
In Ruby:
arr = [:cat,:rat,:cat,:bat,:cat,:cat,:bat,:fat,:mat]
hash = {}
arr.reverse.each_with_index {|item, index| hash[item]=index unless hash.has_key?(item)}
hash
=> {:mat=>0, :fat=>1, :bat=>2, :cat=>3, :rat=>7}