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.
Related
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
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
I have a variable string that might contain any unicode character. One of these unicode characters is the han 𩸽.
The thing is that this "han" character has "𩸽".length() == 2 but is written in the string as a single character.
Considering the code below, how would I iterate over all characters and compare each one while considering the fact it might contain one character with length greater than 1?
for ( int i = 0; i < string.length(); i++ ) {
char character = string.charAt( i );
if ( character == '𩸽' ) {
// Fail, it interprets as 2 chars =/
}
}
EDIT:
This question is not a duplicate. This asks how to iterate for each character of a String while considering characters that contains .length() > 1 (character not as a char type but as the representation of a written symbol). This question does not require previous knowledge of how to iterate over unicode code points of a Java String, although an answer mentioning that may also be correct.
int hanCodePoint = "𩸽".codePointAt(0);
for (int i = 0; i < string.length();) {
int currentCodePoint = string.codePointAt(i);
if (currentCodePoint == hanCodePoint) {
// do something here.
}
i += Character.charCount(currentCodePoint);
}
The String.charAt and String.length methods treat a String as a sequence of UTF-16 code units. You want to treat the string as Unicode code-points.
Look at the "code point" methods in the String API:
codePointAt(int index) returns the (32 bit) code point at a given code-unit index
offsetByCodePoints(int index, int codePointOffset) returns the code-unit index corresponding to codePointOffset code-points from the code-unit at index.
codePointCount(int beginIndex, int endIndex) counts the code-points between two code-unit indexes.
Indexing the string by code point index is a bit tricky, especially if the string is long and you want to do it efficiently. However, it is a do-able, albeit that the code is rather cumbersome.
#sstan's answer is one solution.
This will be simpler if you treat both the string and the data you're searching for as Strings. If you just need to test for the presence of that character:
if (string.contains("𩸽") {
// do something here.
}
If you specifically need the index where that character appears:
int i = string.indexOf("𩸽");
if (i >= 0) {
// do something with i here.
}
And if you really need to iterate through every code point, see How can I iterate through the unicode codepoints of a Java String? .
An ASCII character takes half the amount a Unicode char does, so it's logical that the han character is of length 2. It not an ASCII char, nor a Unicode letter. If it were the second case, the letter would be displayed correctly.
for a college project, I am doing a spelling test for children and i need to give 1 mark for a minor spelling error. For this I am going to do if the spelling has 2 characters wrong. How can I compare the saved word to the inputed word?
char wLetter1 = word1.charAt(0);
char iLetter1 = input1.charAt(0);
char wLetter2 = word1.charAt(1);
char iLetter2 = input1.charAt(1);
I have started out with this where word1 is the saved word and input1 is the user input word.
However, if I add lots of these, if the word is 3 characters long but I am trying to compare the 4th character, I will get an error? Is there a way of knowing how many characters are in the string and only finding the characters of those letters?
Just use a for loop. Since I'm assuming this is about JavaScript, calling charAt() with an index out-of-bounds will just return the empty string "".
To avoid a out-of-bounds exception you'll have to iterate up until the lower of the lengths:
int errs = Math.abs(word1.length - input1.length);
int len = Math.min(word1.length, input1.length);
for (int i = 0; i < len; i++) {
if (word1.charAt(i) != input1.charAt(i)) errs++;
}
// errs now holds the number of character mismatches
Suppose I have a polynomial -x^2 + 2x - 1 = 0. It is read from a file.
I have the code that analyzes each character of the polynomial.
I want to create an extra step that compacts the polynomial(so the white spaces gets eliminated) so I can check if the string is in fact a polynomial which I can easily do by just checking the last 2 index of the polynomial which is the equal sign and the zero like this: (=0)
Problem is some polynomial length have different lengths which gave me the thought to use an ArrayList. Problem is I cannot declare my ArrayList to be of type Character to store each character in the sequential index of an ArrayList.
public void createEquationNoWhiteSpaces(){
// it cannot be done because there is no ArrayList of characters
textArrayList = new ArrayList<String>();
for(int i = 0; i < text.length(); i++){
// Store the characters of the polynomial in an ArrayList
// because each polynomial has different length
if(text.charAt(i) != ' ')
textArrayList = text.charAt(i);
}
}
If you want to use an array, you can certainly declare an ArrayList<Character>. However, you might want to use a StringBuilder instead of a list for this purpose anyway.
st.replaceAll("\\s","")
removes all whitespace in string st