Trying to understand charAt method inside an integer array - java

I am trying to understand, how can we use a string element inside the integer array.
I am solving one of the array related question where I am trying to store frequency of characters in a string.
int[] letters = new int[128];
for(int i = 0; i < s.length(); i++){
System.out.println(s.charAt(i));
letters[s.charAt(i)] = letters[s.charAt(i)] + 1;
}
My question is, since letters is an integer array, s.charAt(i) will return a string character.
I am printing out, letter[s.charAt(i)] which lets say is letters['a'] which does print out a number. But by using charAt its not. How can we access the char as an index?

I am trying to understand, how can we use a string element inside the integer array.
It depends on what you mean in use. If you want to store a string value into integer array - you cannot. Neither int[] or Ingeter[] will allow you to store any string element in them. You will get a compile-time error, something like:
java: incompatible types: java.lang.String cannot be converted to int
I am printing out, letter[s.charAt(i)] which lets say is letters['a']
String#charAt(int) returns a single character, and what you're trying to do, is to access your letters array's slot with a character index, which, in turn, would also stop your compilation process with the message:
java: cannot find symbol
symbol: variable yourCharacter
How can we access the char as an index?
You cannot. Index of any array is always a positive integer number.

Let us say your string is
String str = "stack"
for(int i=0; i<str.length(); i++) {
System.out.println(str.charAt(i))
}
// Signature of charAt method is, charAt(int index). Here, it takes the index of the string as referred by i and prints the character. Your assumption is slightly wrong. You can refer to String class of the official Java documentation to get the better understanding of the methods arguments, what it does and what it returns.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Related

How to replace first and middle char in string

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.

Using a For Loop to set all lower case to uppercase

How do you use a for loop to set all the lower cases of a string into upper cases?
This is what I did, but I get two compiler errors,
The method setCharAt(int, char) is undefined for the type
java.lang.String [line 7]
Array cannot be resolved [line 12]
public static String allUpperCases(String toEncode){
int length = toEncode.length();
for (int i = 0; i < length; i++){
char ch = toEncode.charAt(i);
if (Character.isLowerCase(ch)){
toEncode.setCharAt(i, Character.toUpperCase(ch));
}
}
return toEncode;
}
You can just use a single operation!
my_string = my_string.toUpperCase();
If you just want your String all uppercase, there is a function in Java:
yourstring.toUpperCase();
You don't need to use a for loop to set a string to lower or upper case. You can use myString = myString.toLowerCase();. Conversely, there is the opposite: myString = myString.toUpperCase();. You should really read the String API.
With regards to your errors:
The String type does not have a setCharAt() function in Java. That's because a String, at least in Java, is an immutable type. When you "change" a string, unless you're using a StringBuilder or modifying the underlying char array, you are actually assigning a new String to the variable.
I can't diagnose your Array cannot be resolved error, as I don't see an array in your code.

How do I compare each character of a String while accounting for characters with length > 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.

Getting last few characters from a string

I have a java string containing n number of characters.
How do I extract the LAST few characters from that string?
I found this piece of code online that extracts the first few, but I dont understand it so I cant modify it.
Can anyone help me with this?
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Try,
String upToNCharacters = s.substring(s.length()-lastCharNumber);
That piece of code does exactly the opposite of what you want. Now let's see why and how we can modify it.
Quick solution
You can modify the code as follows to do what you want:
String lastNchars = s.substring( Math.max(0, s.length()-n));
Explanation
According to the official documentation, Java String class has a special method called substring().
The signature of the method is the following (with overload):
public String substring(int beginIndex, int endIndex))
public String substring(int beginIndex)
The first method accepts 2 parameters as input:
beginIndex: the begin index of the substring, inclusive.
endIndex: the end index of the substring, exclusive.
The second overload will automatically consider as endIndex the length of the string, thus returning "the last part"
Both methods return a new String Object instance according to the input parameters just described.
How do you pick up the right sub-string from a string? The hint is to think at the strings as they are: an array of chars. So, if you have the string Hello world you can logically think of it as:
[H][e][l][l][o][ ][w][o][r][l][d]
[0]...............[6]......[9][10]
If you choose to extract only the string world you can thus call the substring method giving the right "array" indexes (remember the endIndex is exclusive!):
String s = "Hello world";
s.substring(6,11);
In the code snippet you provided, you give a special endIndex:
Math.min(s.length(), n);
That is exactly up to the n th char index taking into account the length of the string (to avoid out of bound conditions).
What we did at the very beginning of this answer was just calling the method and providing it with the beginning index of the substring, taking into account the possible overflow condition if you choose a wrong index.
Please note that any String Object instance can take advantage of this method, take a look at this example, for instance:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
As you see even "abc", of course, has the substring method!
Have a look at the substring documentation, Basically what it does is, it returns a substring of the string on which it is called, where substring from the index specified by the first parameter and the ends at the second parameter.
So, to get the last few characters, modify the begin index and the end index to the values you need. There is also another version of this method which takes only one parameter, just the begin index, which might be useful for you.
String lastNchars = s.substring(s.length()-n);
One of the String.substring() overloads takes one parameter - the index of the starting index. From that, you can easily implement your function :
String lastFew(String s, int number) {
if (number > s.length()) {
throw new IllegalArgumentException("The string is too short!");
} else return s.substring(s.length()-number);
}

How to detect polynomials in Java

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

Categories

Resources