Reputation: 93
I want to only remove 'a' in " brealdeke " This program works, it prints " breldeke " but if I were to put " brealdeake" with 2 'a' in this string, it goes berserk and prints : breldeakebrealdeke How to fix it ? Thanks I really want it to look this this :
class Example {
public static String suppression(char c, String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
int position = i;
for (int a = 0; a < position; a++) {
System.out.print(s.charAt(a));
}
for (int b = position + 1; b < s.length(); b++) {
System.out.print(s.charAt(b));
}
}
}
return "";
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeakebrealdeke"
System.out.print(suppression('a', "brealdeake"));
}
}
Upvotes: 1
Views: 85
Reputation: 5140
Additional variables OK?
I'd do it like this personally:
public static String removeFirstLetter(string s, char c)
{
String word = "";
Bool foundChar = false;
for ( int i = 0; i<s.length();i++) {
if (s.charAt(i).toLower() != c)
{
word += s.char(i);
}
else
{
if (foundChar == false){
foundChar = true;
}
else
{
word += s.char(i);
}
}
}
}
System.out.print(word);
Upvotes: 0
Reputation: 794
You could try :
"banana".replaceFirst("a", "");
This returns bnana
EDIT: Hopefully, this doesn't include anything you haven't been taught yet
public static void main(String[] args) {
String word = "banana";
String strippedWord = "";
boolean found = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a' && !found) found = !found;
else strippedWord += word.charAt(i);
}
System.out.println(strippedWord);
}
This prints bnana
EDIT2 : You said you wanted it in a function, the same applies :
public static String suppression(char c, String word) {
String strippedWord = "";
boolean charRemoved = false; // This is a boolean variable used to know when the char was skipped!
for (int i = 0; i < word.length(); i++) {
// If the current letter is for example 'a' and we haven't yet skipped the char, skip this char we're at
if (word.charAt(i) == c && charRemoved == false) charRemoved = true;
else strippedWord += word.charAt(i);
}
return strippedWord;
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeake"
System.out.print(suppression('a', "brealdeake"));
}
Upvotes: 1