Rob Moore Rob Moore - 3 months ago 17
Java Question

Char replacement (without using replace)

This code is a series of tasks, the first is it replace all 'F' in sentence string to a 'f' without using the .replace() method. Which i've done, then after that I'm supposed to replace all the 'f's to blanks, which I sort of done but for some reason all my capital 'F's change to a weird square. Any ideas? I know it's basic code but baby steps.

Here is my weird output: "There was a isherman named []isher who ished or some ish in a issure; till a ish with a grin, pulled the isherman in. Now they’re ishing the issure or []isher."

Thanks! Rob.

public static void main(String[] args) {
// orginal string sentence
String sentence = ("There was a fisherman named Fisher who fished for some fish in a fissure; till a fish with a grin, pulled the fisherman in. Now they’re fishing the fissure for Fisher. ");
// data
char[] originalArray = sentence.toCharArray();
int i = 0;
int sLength = sentence.length();
int positionArray[];
// combining an int to the array position
positionArray = new int[sLength];
/* while loop to check the position of any 'F' or 'f' characters in sentence and identifying it's array position*/
while (i < sLength) {
char charAt = sentence.charAt(i);
if (charAt == 'F') {
originalArray[i] = 0;
positionArray[i] = 1;
}
i++;

}
//redeclaring int i to 0 for the new array
i = 0;
//reassigning the character 'F' or 'f' to just 'f to 'sentence'
sentence = new String(originalArray);
char[] newArray = sentence.toCharArray();
while (i < sLength) {
if (positionArray[i] == 1) {
newArray[i] = 'f';
}
i++;
//redeclaring int i to 0 for the (part e)
i = 0;
//removing every occurance of 'f' (part e)
while (i < sLength) {
if (newArray[i] == 'f' ) {
newArray[i] = ' ';
}
i++;
//printing to console
}
sentence = new String(newArray);
System.out.println(sentence);
}


}

fge fge
Answer

Here is a solution using Java 8. It uses the fact that a String is a CharSequence, and that you can obtain an IntStream of either the characters or code points in it; this solution uses chars:

// Turn all 'F's into 'f's
private int bigFToSmallF(final int inputChar)
{
    return 'F' == inputChar ? 'f' : inputChar;
}

// Turn all 'f's into '0's
private int smallFToZero(final int inputChar)
{
    return 'f' == inputChar ? '0' : inputChar;
}

private String anyFToZeroes(final String input)
{
    final StringBuilder sb = new StringBuilder(input.length());

    input.chars().map(this::bigFToSmallF).map(this::smallFToZero)
        .forEach(sb::appendCodePoint);

    return sb.toString();
}

Plug this code into a main and you're done.

Comments