String type charAt - java

I have two simple examples to support my question. I can't figure out why (1) is working while (2) isn't. In my opinion I use them the same way.
(1)
public String frontBack(String str) {
if (str.length() <= 1) return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
(2)
public String front22(String str) {
str = "test";
return str.charAt(0);
}
With the second one, I get an type mismatch error that says: Cannot convert from char to string. When I try to find an answer on internet I see the str declared as a var type in all examples. But it works with the first example.
What am I missing?

In the first example you return a String. In the second you (try to) return a char.
Since you do string concatenation in the first example the result of the expression is a string.

To return the first character as a String:
return str.substring(0,1);

You can fix it by typing
return "" + str.charAt(0);
Somehow that forces the character into a string.

Related

Recursive method to combine a string and its reverse

everyone. I am very new to java so I hope my question does not sound dumb, but I am encountering trouble with an online exercise.
Basically, I need to write a recursive method, in java, called reverse that accepts a String parameter and returns a string concatenated with its reverse. So, for example, if the string was "Java" it returns it as "JavaavaJ"
I worked out most of the code, but cannot figure out how to combine the two in the return method.
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
You'll want to prepend the string you're reversing with the first character as well. Something like this should work:
public String reverse(String str) {
if (null == str) {
return null;
}
if (str.length() <= 1) {
return str + str;
}
return str.charAt(0) + reverse(str.substring(1)) + str.charAt(0);
}
Without prepending the first character, the recursion would just produce a reverse of the string. Similarly, appending the whole string twice when you are at the last character is needed as well (e.g., "a" reversed using this logic seems like it should produce "aa")

Character swapping

I'm trying to swap the first and last character in a string so what I did was I was able to retrieve its first and last characters but am now having hard times putting them all together:
String name="pera";
char[] c = name.toCharArray();
char first = c[0];
char last = c[c.length-1];
name.replace(first, last);
name.replace(last, first);
System.out.println(name);
Although I am getting for the variable 'first' the value of "p" and for the variable 'last' the value of "a", these methods replace() are not turning up with a valid result as the name stays as it is. Does anyone have any idea on how to finish this?
1) String are immutable in Java. so name.replace(first, last) will not modify name but will return a new String.
2) String#replace(char oldChar, char newChar) replaces all occurrences of oldChar in this string with newChar.
For example:
System.out.println("aaaddd".replace("a","d"));
Will give :
dddddd
Possible solution : If you convert your String to a char[], you can easily swap the characters :
public static String inverseFirstAndLast(String str){
char[] c = str.toCharArray();
Character temp = c[0];
c[0] = c[c.length-1];
c[c.length-1]=temp;
return new String(c);
}
Swapping the first with the last is easy like this:
String str = "SwapDemo";
String swapped = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);
The method you tried will replace all the occurrences of the passed argument, which is not what you want. The code above will do what you want.
As Arnoud pointed out, strings are immutable. But, fixing that issue, you will still get wrong results for:
acbbc
for example
c[0] = last;
c[c.length-1] = first;
System.out.println(new String(c));
Here's a regex based solution:
String str = "demo";
String swapped = str.replaceAll("^(.)(.*)(.)$", "$3$2$1");
Related to solution of #Martijn Courteaux. You can also store the result inside same str String hence saving a little bit of space, like this:
String str = "pera";
String str = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);

How to use recursion to reverse a String?

public String reverse(String word) {
if ((word == null) || (word.length() <= 1)) {
return word;
}
return reverse(word.substring(1)) + word.charAt(0);
}
I have this code that professor sent me but I don't get it. I know what recursion is but I'm still a newbie at Java Programming so if anybody would care to explain to me the part
return reverse(word.substring(1)) + word.charAt(0);
what does the subString(1) does and the chartAt(0)?
This is recursion. Here are documentation for subString() and charAt().
Coming to how this works:
public static String reverse(String word) {
if ((word == null) || (word.length() <= 1)) {
return word;
}
return reverse(word.substring(1)) + word.charAt(0);
}
Pass1: reverse("user") : return reverse("ser")+'u';
Pass2: reverse("ser")+'u' : return reverse("er")+'s'+'u';
Pass3: reverse("er")+'s'+'u' : return reverse("r")+'e'+'s'+'u';
Pass4: reverse("r")+'e'+'s'+'u' : return 'r'+'e'+'s'+'u'; // because here "r".length()==1
The way the recursive part of this works is that to reverse a string, you remove the first character, reverse what's left, and then append the first character to the result. That's what the prof's code is doing.
word.substring(1) returns the substring starting at index 1 and going to the end
word.charAt(0) returns the character at index 0
There's a bit more going on when the two pieces are appended using +. The issue is that word.charAt(0) has a return type of char. Since the left-hand part of the + is a String, the Java language rules say that the right-hand side must be converted to a String if it isn't one. So the char value is first converted to a Character and then the toString() method of the Character class is called. This returns a String consisting of the single character.
It might have been more efficient code to write that line like:
return reverse(word.substring(1)) + word.substring(0, 1);
The two-argument version of substring returns the substring between the two indexes. That would eliminate the autoboxing and conversion to String.
return reverse(word.substring(1)) + word.charAt(0);
you should read it this way:
remove the first letter away from the word
reverse the rest (recursive call)
put the first letter at the end
if you assume this function reverses the strings of length N, you can easily see that it must reverse the strings of length N+1. If you realize that the word with at most one letter is the same if reversed (the first three lines of code), you have a complete very simple proof using Mathematical Induction that this function really reverses the string.

Concatenate a string before the last occurrence of any character

I want to concatenate a string before the last occurrence of any character.
I want to do something like this:
addToString(lastIndexOf(separator), string);
where "ddToString" is a function that would add the "string" before the "lastIndexOf(separator)"
Any ideas?
One way I thought of is making string = string + separator.
But, I can't figure out how to overload the concatenate function to concatenate after a particular index.
You should look in Java's api at http://download.oracle.com/javase/7/docs/api/ and use the String Classes substring(int beginIndex)method after you find the index of your specified character so
public String addToString(String source, char separator, String toBeInserted) {
int index = source.lastIndexOf(separator);
if(index >= 0&& index<source.length())
return source.substring(0, index) + toBeInserted + source.substring(index);
else{throw indexOutOfBoundsException;}
}
Try this:
static String addToString(String source, int where, String toInsert) {
return source.substring(0, where) + toInsert + source.substring(where);
}
You'll probably want to add some parameter checking (in case character isn't found, for instance).
You need to use StringBuffer and method append(String). Java internally converts + between Strings into a temporary StringBuffer, calls append(String), then calls toString() and lets the GC free up allocated memory.
The simple way is:
String addToString(String str, int pos, String ins) {
return str.substring(0, pos) + ins + str.substring(pos);
}

Java - removing first character of a string

In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}

Categories

Resources