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.
Related
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
String message = "a";
char message1 = (char) message;
System.out.println(message1);
Gives me an output error,
This should be converted with ease because the string is one character "a"
I know I can do it explicitly sorry, why the two are incompatible to cast if they are storing the same (only one character)?
As you've seen, no, you cannot cast a single character String to a char. But you could extract it explicitly:
String message = "a";
char message1 = message.charAt(0);
No you cannot do that. You can cast a char to Character because the Character object type is the "boxed" version of the char base type.
Character charObject = (Character) 'c';
char charBase = (char) charObject;
actually, because of auto-boxing and auto-unboxing, you don't need the explicit cast:
Character charObject = 'c';
char charBase = charObject;
However, a String is an object type much like any other object type. That means you cannot cast it to char, you need to use the charAt(int index) method to retrieve characters from it.
Beware though that you may want to use codePointAt(int index) instead, since Unicode code points may well extend out of the 65536 code points that can be stored in the 16 bits that a char represents. So please make sure that no characters defined in the "supplementary planes" are present in your string when using charAt(int index).
As in Java any type can be converted to String, it is possibly to directly append characters to a string though, so "strin" + 'g' works fine. This is also because the + operator for String is syntactic sugar in Java (i.e. other objects cannot use + as operator, you would have to use a method such as append()). Do remember that it returns a new string rather than expanding the original "strin" string. Java strings are immutable after all.
You cannot cast a String to a char. Below is a snippet to always pick the first character from the String,
char c = message.charAt(0);
In case you want to convert the String to a character array, then it can be done as,
String g = "test";
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['t','e','s','t']
A String with one char is more akin to a char[1]. Regardless, retrieve the character directly:
String ex = /* your string */;
if (!ex.isEmpty()) {
char first = ex.charAt(0);
}
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.
As an example I have abcdbab and I want to replace all ab with A.
The output is AcdbA.
I try this one but it gives an error.
char N = 65;
String S = "abcdbab";
S = S.replaceAll("ab", N);
System.out.print(S);
Is there any method to do this?
Use String.replace(CharSequence,CharSequence) (remember String is immutable, so either use the result or assign it back) like
String str = "abcdbab";
System.out.println(str);
str = str.replace("ab", "A");
System.out.println(str);
Output is
abcdbab
AcdbA
Just change the following line:
char N = 65;
to
String N = "A";
and it'll work fine.
There is no such method String#replace(CharSequence, char), you will need to find the one that is closes to your needs and adjust to it, for example, there is a String#replaceAll(CharSequence, CharSequence) method and char can be represented as a CharSequence (or a String), for example...
S = S.replaceAll("ab", Character.toString(N));
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
You can also change
S = S.replaceAll("ab", N);
to
S = S.replaceAll("ab", "" + N);
referencing here, http://www.tutorialspoint.com/java/java_string_replaceall.htm replaceAll takes a String, String not String, Char
I have some 'heavy' string manipulation in my Java program, which often involves iterating through a String and replacing certain segments with filler characters, usually "#". These are characters are later removed but are used so that the length of the String and the current index are kept intact during the iteration.
This process usually involves replacing more than 1 character at a time.
e.g.
I might need to replace "cat" with "###" in the string "I love cats", giving "I love ###s",
So often I need to create strings of "#" with x length.
In python, this is easy.
NewString = "#" *x
In Java, I find my current method revolting.
String NewString = "";
for (int i=0; i< x; i++) {
NewString = NewString.concat("#"); }
Is there a proper, pre-established method for doing this?
Does anybody have a shorter, more 'golfed' method?
Thanks!
Specs:
Java SE (Jre7)
Windows 7 (32)
It's not clear to me what kind of regex the comments are suggesting, but creating a string filled with a particular character to the given length is pretty easy:
public static String createString(char character, int length) {
char[] chars = new char[length];
Arrays.fill(chars, character);
return new String(chars);
}
Guava has a nice little method Strings.repeat(String, int). Looking at the source of that method, it basically amounts to this:
StringBuilder builder = new StringBuilder(string.length() * count);
for (int i = 0; i < count; i++) {
builder.append(string);
}
return builder.toString();
Your way of building a string of length N is very inefficient. You should either use StringBuffer with its convenient append method, or build an array of N characters, and use the corresponding constructor of the String.
Can you always use the same characters in the "filler" String and do you know the maximum value of x? The you can create a constant upfront which can be cut to arbitrary length:
private static final FILLER = "##############################################";
// inside your method
String newString = FILLER.substring(0, x);
java.lang.String is immutable. So, concating strings would result in creation of temporary string objects and thus is slow. You should consider using a mutable buffer like StringBuffer or StringBuilder. Another best practice when working with strings in java is to prefer using CharSequence type wherever possible. This would avoid unnecessary calls to toString() and you can easily change the underlying implementation type.
If you are looking for a one liner to repeat strings and this justifies using an external library, have a look at StringUtils.repeat from Apache Commons library. But, I feel you can just write your own code than using another library for a trivial task of repeating strings.