Understanding the method removeChar - java

At school we were looking at a code for removing a character from a string.
I have a problem understanding the for loop in this code.
What happens if word.charAt(i) is equal to c? If word.charAt(i) is not equal to c the character is printed out. (words.charAt(i) gets printed out)
But if it is equal to c, where in the code does the character get removed?
Thank you in advance for your help. And I'm sorry for my bad English.
This is the code our teacher gave us:
String removeChar(String word, char c) {
String result = "";
for (int i = 0; i<word.length();i++) {
if (word.charAt(i) !=c) {
result += word.charAt(i);
}
}
return result;
}

You can read this code like:
Create an empty String result.
For each letter from word, check if it is not 'c' character. Only if it is not 'c', append this letter to result String (add this letter at the end of result String). If currently checked character is equal to 'c', do nothing.
When loop reaches the end of word, return result String.
By the way, appending String in a loop using += operator is not that efficient like using class StringBuilder and its append() method.

The char is not really removed;
it's simply not append (result += word.charAt(i)) into the string result.
In this way the string that is returned by the method is formed only by the chars that are different from char c.

This code just creates new String object (see variable result). At end of function this new string contains only characters which do not equal to c. Next it string returns as result of function.
Java strings is not mutable, so this is only way to "modify" string - create brand new string.

Character is not actually removed its just been appended to the empty new string(String result = "";) which you have declared above,when word doesn't contain the character 'c', then those characters are getting appended to result, finally you are retrieving that 'Result' string not 'Word',it still containing same value which you have sent.

Related

CodingBat - Java - Warmup-2 - "stringYak" algorithm

I'm presently trying to understand a particular algorithm at the CodingBat platform.
Here's the problem presented by CodingBat:
*Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
Example outputs:
stringYak("yakpak") → "pak"
stringYak("pakyak") → "pak"
stringYak("yak123ya") → "123ya"*
Here's the official code solution:
public String stringYak(String str) {
String result = "";
for (int i=0; i<str.length(); i++) {
// Look for i starting a "yak" -- advance i in that case
if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
i = i + 2;
} else { // Otherwise do the normal append
result = result + str.charAt(i);
}
}
return result;
}
I can't make sense of this line of code below. Following the logic, result would only return the character at the index, not the remaining string.
result = result + str.charAt(i);
To me it would make better sense if the code was presented like this below, where the substring function would return the letter of the index and the remaining string afterwards:
result = result + str.substring(i);
What am I missing? Any feedback from anyone would be greatly helpful and thank you for your valuable time.
String concatenation
In order to be on the same page, let's recap how string concatenation works.
When at least one of the operands in the expression with plus sign + is an instance of String, plus sign will be interpreted a string concatenation operator. And the result of the execution of the expression will be a new string created by appending the right operand (or its string representation) to the left operand (or its string representation).
String str = "allow";
char ch = 'h';
Object obj = new Object();
System.out.println(ch + str); // prints "hallow"
System.out.println("test " + obj); // prints "test java.lang.Object#16b98e56"
Explanation of the code-logic
That said, I guess you will agree that this statement concatenates a character at position i in the str to the resulting string and assigns the result of concatenation to the same variable result:
result = result + str.charAt(i);
The condition in the code provided by coding bat ensures whether the index i+2 is valid and then checks characters at indices i and i+2. If they are equal to y and k respectively. If that is not the case, the character will be appended to the resulting string. Athowise it will be discarded and the indexed gets incremented by 2 in order to skip the whole group of characters that constitute "yak" (with a which can be an arbitrary symbol).
So the resulting string is being constructed in the loop character by characters.
Flavors of substring()
Method substring() is overload, there are two flavors of it.
A version that expects two argument: the starting index inclusive, the ending index, exclusivesubstring(int, int).
And you can use it to achieve the same result:
// an equivalent of result = result + str.charAt(i);
result = result + str.substring(i, i + 1);
Another version of this method, that expects one argument will not be useful here. Because the result returned by str.substring(i) will be not a string containing a single character, but a substring staring from the given index, i.e. encompassing all the characters until the end of the string as documentation of substring(int) states:
public String substring(int beginIndex)
Returns a string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
Side note:
This coding-problem was introduced in order to master the basic knowledge of loops and string-operations. But actually the simplest to solve this problem is by using method replaceAll() that expects a regular expression and a replacement-string:
return str.repalaceAll("y.k", "");

Having trouble with what to write as my return?

I'm writing a caesar encryption method. For every character of the original string, I want my method to shift the character by three. For example, 'A' shifted to 'D' and so forth. Now I want to combine all the shifted characters in a single string (encrypted message) and return it.
How do I write statements to combine the characters and then return it.
You have to concatenate all the characters to form a string. Then return the string.
At first you declare a String object:
String result ="";
Inside the for loop, after the if-else statement, you add the shifted character to your resultant string:
result = result + t;
Then in the end (outside for loop) you return the resultant string:
return result;
And if you wanna use StringBuilder:
Create a StringBuilder object:
StringBuilder builder = new StringBuilder();
Append character:
builder.append('a'); or
char t = 'b';
builder.append(t);
Convert to String and return:
return builder.toString();
To return an encrypted message you can recursively call your own method with the message. Make sure you have a condition on when you should return null (or in this case your own message).
One small problem with your loop is you just shift the char t but not replace in to a string or make your return string. You should store your result somewhere.

Removing letters from a string using a while loop in Java

while (sentence.indexOf(lookFor) > lookFor)
{
sentence += sentence.substring(sentence.indexOf(lookFor));
}
String cleaned = sentence;
return cleaned;
This is what I have tried to do in order to remove letters. lookFor is a char that was put in already, and sentence is the original sentence string that was put in already. Currently, my code outputs the sentence without doing anything to it.
EX Correct Output: inputting "abababa" sentence; char as "a" --->outputting "bbb"
inputting "xyxyxy" sentence; char "a" ---> outputting "xyxyxy"
You don't need while for a single string. Only if you read a text line after line.
In your case something like
String a = "abababa";
a = a.replace("a","");
would give you the output "bbb"
it probably isn't entering the loop at all.
sentence.indexOf(lookFor) is going to return the place of the character in the string.
lookFor is a char value. A value of 'a' has a numeric value of 97 so the while will only find things after the first 97 characters.
If your code ever entered the loop it would never return.
the substring command you are calling will take the found item to the end of the string.
+=, if it did what you think will append it to itself. so it will take 'ababab' and make it 'abababababab', forever. but luckily you can't use += on a string in java.
What you want is:
String something = "abababab";
something = something.replaceAll("a", "");
If you just need to get rid of letters use the replace method that others have written, but if you want to use a while loop, based on what I've seen of your logic, this is how you'd do it.
while (sentence.indexOf(lookFor) == 0)
sentence = sentence.substring(1);
while (sentence.indexOf(lookFor) > 0)
{
sentence = sentence.substring(0, sentence.indexOf(lookFor)-1)+
sentence.substring(sentence.indexOf(lookFor)+1);
}
return sentence;

In Java String, How to cut a part of a String by just 1 line of code (probally use Regex)?

given this string http://verylongurlverylonngurl/image.jpg & I wanna cut all the part before the last "/". For example, I wanna remove the part http://verylongurlverylonngurl/ of the string above. The result will be "image.jpg".
I have to cut the String "Label" & the code to cut that String must be inside the super() keyword & super keyword must be the first statement in the constructor. Loook at this code:
private class TextShortenedCheckBox extends CheckBox{
private String originalText;
public TextShortenedCheckBox(String label, int visibleLength){
super(label.substring(label.length()-9,label.length()-1));
originalText=label;
}
#Override
public String getText(){
return originalText;
}
}
Look at the code: label.substring(label.length()-9,label.length()-1) this code give the result but not be able to apply for other variable string.
So, how to cut a part of a String by just 1 line of code, so that I can put that code inside super(). Maybe we have to use Regex or something?
What about
str = str.substring(str.lastIndexOf("/") + 1);
Try this:
String str ="http://verylongurlverylonngurl/image.jpg";
str = str.substring(str.lastIndexOf("/")+1);
System.out.println(str);
Output:
image.jpg
You can use lastIndexOf('/')
Returns the index within this string of the last occurrence of the specified character. For values of ch in the range from 0 to 0xFFFF (inclusive), the index (in Unicode code units) returned is the largest value k such that: this.charAt(k) == ch is true. For other values of ch, it is the largest value k such that: this.codePointAt(k) == ch is true. In either case, if no such character occurs in this string, then -1 is returned. The String is searched backwards starting at the last character.

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