I have to write a method that takes in a String and returns a new string that duplicates all vowels and puts a "b" in between. Only exception goes for diphtongs where "ab" should be put in front of the diphtong.
For example: "hello" would return "hebellobo"
"hearing" would return "habearing"
I've experimented with my code for hours but I am not getting anything done.
Well, not anything, but can't make it run properly for vowels and didn't get to the diphtongs at all.
Here is my code:
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter a string: ");
String s = sc.nextLine();
String originalString = s;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i') || (c == 'O')
|| (c == 'o') || (c == 'U') || (c == 'u'))
{
String front = s.substring(0, i);
String back = s.substring(i + 1);
s = front + c + "b" + back;
}
}
System.out.println(originalString);
System.out.println(s);
}
Grateful for any help !
Thanks to your help I now have the following code (without Scanner):
public static boolean isVowel(char c) {
// TODO exercise 1 task b) part 1
if (c == 'a' || c == 'A' || c == 'Ä' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O'
|| c == 'Ö' || c == 'u' || c == 'U' || c == 'Ü') {
return true;
} else {
return false;
}
}
public static String toB(String text) {
// TODO exercise 1 task b) part 2
StringBuilder b = new StringBuilder();
for (int i = 0; i < text.length() - 1; i++) {
char current = text.charAt(i);
char next = text.charAt(i + 1);
if (isVowel(current)) {
if (isVowel(next)) {
// 1 - Is a vowel followed by a vowel
// Prepend b
b.append("b");
// Write current
b.append(current);
// Write next
b.append(next);
i++; // Skip next vowel
} else {
// 2 - Is a vowel followed by a consonant
b.append(current);
b.append("b");
b.append(current);
}
} else {
// 3 - Is a consonant
b.append(current);
}
}
for (int i = 0; i < text.length() - 1; i++) {
char last = text.charAt(text.length() - 1);
char current = text.charAt(i);
if (isVowel(last)) {
// Case 1
b.append(current);
b.append("b");
b.append(current);
// Case 2 is not possible for last letter
} else {
// Case 3
b.append(last);
}
}
// Here b.toString() is the required string
return b.toString();
}
If you put in the word "Mother" for example, the ouput is "Mobotheberrrrr" which is perfectly fine, except that it repeats the last letter 'r' for some reason. Input "Goal" results in Output "Gboalll" unfortunately.
You need to know the current letter and also the next letter.
In your code you take in consideration only the current letter.
Here is a skeleton code to solve the problem.
Basically you need to check:
If the current letter is a vowel followed by a vowel
If the current letter is a vowel followed by a consonant
If the current letter is a consonant
String originalString = ...
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
char current = s.charAt(i);
char next = s.charAt(i + 1);
if (isVowel(current)) {
if (isVowel(next)) {
// 1 - Is a vowel followed by a vowel
// Prepend b
b.append("b");
// Write current
b.append(current);
// Write next
b.append(next);
i++; // Skip next vowel
} else {
// 2 - Is a vowel followed by a consonant
b.append(current);
b.append("b");
b.append(current);
}
} else {
// 3 - Is a consonant
b.append(current);
}
}
char last = s.charAt(s.length() - 1);
if (isVowel(last)) {
// Case 1
b.append(current);
b.append("b");
b.append(current);
// Case 2 is not possible for last letter
} else {
// Case 3
b.append(last);
}
// Here b.toString() is the required string
Please consider this only as a skeleton, in particular:
check for border conditions
implements the method isVowel
check for null and empty strings
Note: the use of StringBuilder is only for performance reasons, using directly the String s will give the same result
My best guess is make a chain of replaceAlls because you are basically replacing vowels with duplicates and bs so try something like so:
String original = something;
String adjusted = original.replaceAll("ea","abea").replaceAll("a","aba").replaceAll(...)...;
And just fill in the rules. Make sure to check diphthongs before checking single vowels or they will be treated as two single vowels
Related
I need to find the number of distinct vowels. I came up with the code below but it can't make distinction between same vowels:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}
I would start with five variables (one for each vowel) set to 0, iterate the characters in the input and set the corresponding variable to 1 if I find a match, and simply return the accumulated value of said variables. Like,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}
You could use Set data structure and instead of incrementing the counter just add vowels to the set. At the end you can return just the size of the set.
The problem in your code is that you are not counting the distinct vowels, but all the vowels in the string. A Java-8 way to this:
public static int countDistinctVowels(String str) {
str = str.toLowerCase();
int count = (int) str.chars() // get IntStream of chars
.mapToObj(c -> (char) c) // cast to char
.filter(c -> "aeiou".indexOf(c) > -1) // remove all non-vowels
.distinct() // keep the distinct values
.count(); // count the values
return count;
}
Also use proper Java naming conventions: countDistinctVowels, no count_Distinct_Vowels.
there's definitely an issue here with this counting. at the very least. you should rethink this:
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
You could use the method contains
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
count += string.contains("a") ? 1 : 0;
count += string.contains("e") ? 1 : 0;
count += string.contains("i") ? 1 : 0;
count += string.contains("o") ? 1 : 0;
count += string.contains("u") ? 1 : 0;
return count;
}
I made explanations in the comments to the code:
public static int count_Vowels(String str) {
str = str.toLowerCase();
Set<Character> setOfUsedChars = new HashSet<>(); // Here you store used vowels
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') { // if currently checked character is vowel...
setOfUsedChars.add(str.charAt(i)); // add this vowel to setOfUsedChars
}
}
return setOfUsedChars.size(); // size of this sets is a number of vowels present in input String
}
static void vow(String input){
String output=input.toLowerCase();
int flaga=0,flage=0,flagi=0,flago=0,flagu=0;
for(int i=0;i<input.length();i++) {
if((output.charAt(i))=='a' && flaga==0) {
System.out.print(input.charAt(i)+" ");
flaga++;
}
if(output.charAt(i)=='e' && flage==0) {
System.out.print(input.charAt(i)+" ");
flage++;
}
if(output.charAt(i)=='i' && flagi==0) {
System.out.print(input.charAt(i)+" ");
flagi++;
}
if(output.charAt(i)=='o' && flago==0) {
System.out.print(input.charAt(i)+" ");
flago++;
}
if(output.charAt(i)=='u' && flagu==0) {
System.out.print(input.charAt(i)+" ");
flagu++;
}
}
}
public static void main(String args[]) {
String sentence;
int v=0,c=0,ws=0;
Scanner sc= new Scanner(System.in);
sentence = sc.nextLine();
sc.close();
sentence.toLowerCase();
String res="";
for(int i=0;i<sentence.length();i++) {
if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'||sentence.charAt(i)=='i'||sentence.charAt(i)=='o'||sentence.charAt(i)=='u') {
if(res.indexOf(sentence.charAt(i))<0) {
res+=sentence.charAt(i);
v++;
}//System.out.println(res.indexOf(sentence.charAt(i)));
}
else if(sentence.charAt(i)==' ')
ws++;
else c++;
}
System.out.println(res);
System.out.println("no of vowels: "+v+"\n"+"no of consonants: "+c+"\n"+"no of
white spaces: "+ws);
}
You can use this Method to Find Count of Distinct vowels.
public static int count_Vowels(String str) {
char[] c = str.toLowerCase().toCharArray();
int Counter=0;
String NewString="";
for(int i=0;i<c.length;i++){
String tempString="";
tempString+=c[i];
if(!NewString.contains(tempString) && (c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')){
Counter++;
NewString+=c[i];
}
}
return Counter;
}
Here is a solve for this problem without using objects. It's a crude but great solve for beginners who encounter this problem with limited js experience.
How to count unique vowels is a string;
function hasUniqueFourVowels(str){
let va = 0
let ve = 0
let vi = 0
let vo = 0
let vu = 0
let sum = 0
for(let i = 0; i < str.length; i++){
let char = str[i];
if(char === "i"){
vi = 1
}
if(char === "e"){
ve = 1
}
if(char === "a"){
va = 1
}
if(char === "o"){
vo = 1
}
if(char === "u"){
vu = 1
}
sum = va + vi + vo + ve + vu
if (sum >= 4){
return true
}
}
return false
}
#Test
public void numfindVoweles(){
String s="aeiouaedtesssiou";
char a[]=s.toCharArray();
HashMap<Character,Integer> hp= new HashMap<Character, Integer>();
for(char ch:a){
if(hp.containsKey(ch) && (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')){
hp.put(ch,hp.get(ch)+1);
}
else if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
hp.put(ch,1);
}
}
System.out.println(hp);
}
I am trying to develop a method to reverse the vowels in a string. For this, I have developed my own small stack. I am iterating backwards through the string twice, once to populate the stack with each vowel I locate, the second time to replace the vowel with the vowel stored at the top of the stack. I have added a bunch of print statements to determine where this is failing and it seems to be failing at the setCharAt method. For testing purposes, I provide a string aeiou and I am expecting to get back uoiea. The chars are getting replaced during each iteration, but unfortunately, they don't stay that way. As of the next iteration, the chars that were replaced on the previous iteration return to what they were before. As a result, I am getting back ueiou, where only the first character in the string is as expected (and the third which is a noop). Here is my code. Any tips are appreciated.
import java.util.*;
public class Solution {
static String result;
static class StackOfVowels {
static Node top;
public StackOfVowels() {
Node top = null;
}
static class Node {
Node next = null;
char vowel = '\0';
Node(char value) {
this.vowel = value;
}
}
public void push(char item) {
Node node = new Node(item);
if (top == null) {
top = node;
}
else {
node.next = top;
top = node;
}
}
public char top() {
if (top == null) throw new EmptyStackException();
return top.vowel;
}
public void pop() {
int result = -1;
if (top != null) {
result = top.vowel;
top = top.next;
}
}
}
public static String reverseVowels(String s) {
StackOfVowels stackOfVowels = new StackOfVowels();
for(int i = s.length()-1; i >= 0; i--) {
char c = s.charAt(i);
if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
System.out.println("Initial sequence of iterations identified vowel: " + c);
stackOfVowels.push(c);
System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
}
}
for(int j = s.length()-1; j >= 0; j--) {
char b = s.charAt(j);
if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
System.out.println("Second sequence of iterations identified vowel: " + b);
StringBuilder newstr = new StringBuilder(s);
char d = stackOfVowels.top();
System.out.println("Variable d set to top of: " + stackOfVowels.top());
newstr.setCharAt(j, d);
result = newstr.toString();
System.out.println("Here is the new string: " + result);
stackOfVowels.pop();
System.out.println("Stack was popped");
}
}
return result;
}
public static void main(String[] args) {
String s = "aeiou";
reverseVowels(s);
System.out.println("Final result: " + result);
}
}
A slight improvement (debatable) on #Elliot answer is to create the StringBuilder with the original String and only replace when necessary
String vowels = new StringBuilder(s.replaceAll("[^AEIOUaeiou]", ""))
.reverse().toString();
StringBuilder sb = new StringBuilder(s);
for (int i = 0, p = 0; i < s.length(); i++) {
switch (Character.toLowerCase(s.charAt(i))) {
// Note that these fall-through...
case 'a': case 'e': case 'i': case 'o': case 'u':
sb.setCharAt(i, vowels.charAt(p++));
break;
default:
break;
}
}
return sb.toString();
You generate always a new StringBuilder in your second loop with StringBuilder newstr = new StringBuilder(s);
But you always use ´s´ and not ´result´ to build your new StringBuilder.
It would be better anyways to not create a new Object of StringBuilder in each Iteration.
Also it is confusing that your methode has a return value, which is never used.
Following methode should work:
public static String reverseVowels(String s) {
StackOfVowels stackOfVowels = new StackOfVowels();
for(int i = s.length()-1; i >= 0; i--) {
char c = s.charAt(i);
if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
System.out.println("Initial sequence of iterations identified vowel: " + c);
stackOfVowels.push(c);
System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
}
}
StringBuilder result_builder = new StringBuilder(s);
for(int j = s.length()-1; j >= 0; j--) {
char b = s.charAt(j);
if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
System.out.println("Second sequence of iterations identified vowel: " + b);
char d = stackOfVowels.top();
System.out.println("Variable d set to top of: " + stackOfVowels.top());
result_builder.setCharAt(j, d);
stackOfVowels.pop();
System.out.println("Stack was popped");
}
}
result = result_builder.toString();
return result_builder.toString();
}
I would approach the problem a little differently, first I would use a regular expression to remove all consonants from the String to create a String of vowels. Then I would iterate through the characters of the String, using StringBuilder to build the output (passing consonants through, but replacing vowels using the vowels String previously created). Like,
public static String reverseVowels(String s) {
// Match all consonants, and remove them. Reverse that String.
String vowels = new StringBuilder(s.replaceAll("[^AEIOUaeiou]", ""))
.reverse().toString();
StringBuilder sb = new StringBuilder();
for (int i = 0, p = 0; i < s.length(); i++) {
switch (Character.toLowerCase(s.charAt(i))) {
// Note that these fall-through...
case 'a': case 'e': case 'i': case 'o': case 'u':
sb.append(vowels.charAt(p++));
break;
default:
sb.append(s.charAt(i));
}
}
return sb.toString();
}
This is one of the places that switch and fall-through behavior can be taken advantage of.
And if you're using Java 8+, you could express the same with an IntStream and map the characters; like
String vowels = new StringBuilder(s.replaceAll("[^AEIOUaeiou]", ""))
.reverse().toString();
int[] counter = new int[1]; // <-- A bit of a kludge really.
return IntStream.range(0, s.length()).mapToObj(i -> {
switch (Character.toLowerCase(s.charAt(i))) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return Character.toString(vowels.charAt(counter[0]++));
default:
return Character.toString(s.charAt(i));
}
}).collect(Collectors.joining());
I am trying a program that translates your sentence into pig latin. Here's the code I have so far:
public class PigLatin {
public static void main(String[] args) {
//Enter text in the quotes of System.ot.println(covertToLatin(" "));
System.out.println(covertToLatin("Type your sentence here."));
}
private static String covertToLatin(String string) {
String end = "";
String delims = "\\s+";
String[] words = string.split(delims);
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
end += words[i].substring(1) + words[i].substring(0, 1) + "ay";
}
}
return end;
}
private static boolean isVowel(char c) {
if (c == 'a')
return true;
if (c == 'e')
return true;
if (c == 'i')
return true;
if (c == 'o')
return true;
if (c == 'u')
return true;
return false;
}
}
It translates "Type your sentence here." to "ypeTayouryayentencesayere.hay" I am stumped as to finding a way to translate my whole sentence. can you please help me translate a whole sentence into pig latin? Also, it would help if you could find a way to make the sentence convert in all caps too.
for upper case, use String.toUpperCase() function
Start by translating one word first and then a complete sentence. For example STACK should print out ACKSTAY. Your program prints out TACKSAY.
Why is this? Let's look at your logic:
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
/*substring(1) is always 1 &&
you add substring(0,1) which is always the interval (0,1) they never change*/
end += words[i].substring(1) + words[i].substring(0, 1) +ay";
}
}
return end.toUpperCase();
}
private static boolean isVowel(char c) {
if ((c == 'a') | (c == 'e') | (c == 'i') | (c == 'o') | (c == 'u'))
return true;
return false;
}
Try writing your algorithm on paper first. For example always using the word stack.
First letter is an s (not a vowel) let's save it in a temp string.
second letter is t ( not a vowel) let's save it in a temp string.
a is a vowel! we print from a onwards + letters in temp + ay
end result = "ack" + "st" + "ay"
abstracting --> substring(i, endOfString) + substring(k,i) + "AY
so you actually need two counters! i,k used to print substring(i,EndOfString) and substring(i,k) which represents the temp array
This program is supposed to compare "DNA" strings.
Input:
3
ATGC
TACG
ATGC
CGTA
AGQ
TCF
First line represents how many times the program will be run. Each time it runs, it compares the two strings. A matches with T and vice versa. G matches with C and vise versa. So if the first letter of string 1 is A, the first letter of string 2 should be T. If the next one is T, the next one on the other string should be A and etc. If a letter other than A, T, G, or C appear, it is a bad sample. If its bad, print out bad, if its good, print out good. I tried many different combinations to this and they all worked fine but according the the judge's test data (they have different input), it failed. Does anyone see anything wrong with this? I know it might not be the most efficient way of getting the job done but it did, at least to my understanding.
Output:
GOOD
BAD
BAD
public class DNA
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner (new File ("dna.dat"));
int T = scan.nextInt();
scan.nextLine();
boolean valid = true;
for (int i = 0; i < T; i++)
{
String strand1 = scan.nextLine();
strand1 = strand1.toUpperCase();
String strand2 = scan.nextLine();
strand2 = strand2.toUpperCase();
for (int p = 0; p < strand1.length(); p++)
{
if (strand1.charAt(p) != 'A' && strand1.charAt(p) != 'T' && strand1.charAt(p) != 'G' && strand1.charAt(p) != 'C'
&& strand2.charAt(p) != 'A' && strand2.charAt(p) != 'T' && strand2.charAt(p) != 'G' && strand2.charAt(p) != 'C')
{
valid = false;
break;
}
if (strand1.length() != strand2.length())
{
valid = false;
break;
}
}
if (valid)
{
for (int p = 0; p < strand1.length(); p++)
{
if ((strand1.charAt(p) == 'A' && strand2.charAt(p) == 'T') || (strand1.charAt(p) == 'T' && strand2.charAt(p) == 'A')
|| (strand1.charAt(p) == 'G' && strand2.charAt(p) == 'C') || (strand1.charAt(p) == 'C' && strand2.charAt(p) == 'G'))
valid = true;
else
valid = false;
}
}
if (valid)
out.println("GOOD");
else
out.println("BAD");
valid = true;
}
}
}
I added the toUpperCase and compared the strings for equal length just as a last attempt to see if their data maybe had some lowercase letters or different length strings though they SHOULD all be the same length and uppercase. Nevertheless, the program was still rejected for "failing the judges test data."
You need a break in the second for loop when valid = false. For example if characters 1,2,3 are wrong but #4 is a match you will still end up with valid.
I would convert the strings to arrays to make things easier:
for (int i = 0; i < T; i++)
{
boolean valid = true;
String strand1 = scan.nextLine();
strand1 = strand1.toUpperCase();
String strand2 = scan.nextLine();
strand2 = strand2.toUpperCase();
if ( strand1.length() != strand2.length())
{
valid = false;
}
if (valid) {
char[] c1 = strand1.toCharArray();
char[] c2 = strand2.toCharArray();
for (int p = 0; p < c1.length; p++)
{
if (-1 == "ACTG".indexOf(c1[p]) || -1 == "ACTG".indexOf(c2[p]))
{
valid = false;
break;
}
}
if (valid)
{
for (int p = 0; p < c1.length; p++)
{
if (('A' == c1[p] && 'T' != c2[p]) ||
('T' == c1[p] && 'A' != c2[p]) ||
('C' == c1[p] && 'G' != c2[p]) ||
('G' == c1[p] && 'C' != c2[p])) {
valid = false;
break;
}
}
}
}
if (valid)
System.out.println("GOOD");
else
System.out.println("BAD");
}
Change all
&&
in
if (strand1.charAt(p) != 'A' && strand1.charAt(p) != 'T' && strand1.charAt(p) != 'G' && strand1.charAt(p) != 'C' && strand2.charAt(p) != 'A' && strand2.charAt(p) != 'T' && strand2.charAt(p) != 'G' && strand2.charAt(p) != 'C')
to
||
if ANY, not ALL character is other than A, T, G, or C, then we exit the loop.
I am trying to figure out how to remove certain characters to make it English after it being in l33t speak. For example, I 54w 3 5hip5, would translate to I saw 3 ships. I need the 3 to stay a 3 here but in, N3v3r f0rg37 y0|_|r t0w31, I would need the 3's to become e's. Here is my code as follows. All the characters translate over correctly, but I just can't figure out how to do the 3's to e's.
My question is, what is needed to be added to get the 3's to be e's at a certain time, and to have my 3's stay 3's another time. Just so that you know, is that we aren't allowed to use regex, arrays, or string builder for this.
Rules are that if the number is supposed to be a number that it stays a number when you translate it from l33t to English, if the l33t number is a letter than you replace the number and turn it into the letter that corresponds to it.
I also have a different block of code that already takes into consideration the 3 to e's, but instead adds two u's instead of one.
Here are the replacements for the letters, a = 4, b = 8, e = 3, l = 1, o = 0, s = 5, t = 7, u = |_|, z = 2.
I decided to go the route of mike's answer since I understand exactly what's going on.
Thanks to everyone for the help!
Input/Output examples
This following code translates
I 54w 3 5hip5
to
I saw 3 ships
and
3 5hip5 4r3 c0ming m3 w4y
to
3 ships are coming me way
Code
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
boolean threeAtBeginning = false, threeAtEnd = fal;
if (phrase.charAt(0) == '3' && phrase.charAt(1) == ' ')
threeAtBeginning = true;
int length = phrase.length();
if (phrase.charAt(length - 1) == '3' && phrase.charAt(length - 2) == ' ')
threeAtEnd = true;
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if (threeAtBeginning)
finished = '3' + finished.substring(1);
if (threeAtEnd)
finished = finished.substring(0, length - 1) + '3';
return finished;
}
This is clearly homework, and the restrictions are clearly intended to prevent any sane solution, but here's an O(n^2) solution that seems to avoid the restrictions:
public class RemoveL33t {
public static void main(String[] args) {
System.out.println(removeL33t("I 54w 3 5hip5"));
System.out.println(removeL33t("I 54w 33 5hip5"));
System.out.println(removeL33t("I 54w 45 5hip5"));
System.out.println(removeL33t("N3v3r f0rg37 y0|_|r t0w31"));
}
public static String removeL33t(String s) {
String result = "";
for (int pos = 0;;) {
// Find the beginning of the next word.
int whitespaceBegin = pos;
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
// Add the whitespace to the result.
result += s.substring(whitespaceBegin, pos);
// If there is no next word, then we're done.
if (pos >= s.length()) {
return result;
}
// Find the end of the word. Determine if the word is entirely numbers.
int wordBegin = pos;
boolean nonNumber = false;
while (pos < s.length() && !Character.isWhitespace(s.charAt(pos))) {
nonNumber |= s.charAt(pos) < '0' || s.charAt(pos) > '9';
pos++;
}
// Append the word. Perform replacements if it contains a non-number.
if (nonNumber) {
result += s.substring(wordBegin, pos)
.replace('4', 'a')
.replace('8', 'b')
.replace('3', 'e')
.replace('1', 'l')
.replace('0', 'o')
.replace('5', 's')
.replace('7', 't')
.replace("|_|", "u")
.replace('2', 'z');
} else {
result += s.substring(wordBegin, pos);
}
}
}
}
I think this is it.
public static String translateToEnglish(String phrase) {
if (phrase == null) {
return null;
}
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if(finished.startsWith("e ")){
finished = "3 " + finished.substring(2);
}
if(finished.endsWith(" e")){
finished = finished.substring(0, finished.length()-2) + " 3";
}
return finished;
}
I don't know if this is the answer, but is the best i could think of
public static void main (String[] args) throws java.lang.Exception
{
String c = "I 54w 45 5hip5";
for(String s: c.split(" ")){
try{
Integer.parseInt(s);
System.out.print(s + " ");
}
catch(NumberFormatException e){
s = s.replace('4', 'a').replace('1', 'l').replace('2', 'z').replace('5', 's').replace('8', 'b').replace('0', 'o').replace('7', 't').replace("|_|", "u").replace("3", "e");
System.out.print(s + " ");
}
}
}
This is for your "new" code that you decided to use, or this could just be an alternate solution. The input/output is identical to the samples I gave in my other answer:
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
String finished = "";
for (int i = 0; i < phrase.length(); i++) {
char c = phrase.charAt(i);
if (c == '4')
finished += 'a';
else if (c == '3') {
if (i != phrase.length() - 1)
{
if (phrase.charAt(i + 1) == ' ') {
if (i == 0)
finished += c;
else
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
else
finished += 'e';
}
else
{
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
} else if (c == '1')
finished += 'l';
else if (c == '2')
finished += 'z';
else if (c == '5')
finished += 's';
else if (c == '7')
finished +='t';
else if (c == '8')
finished += 'b';
else if (c == '0')
finished += 'o';
else if (i + 2 < phrase.length() && phrase.charAt(i + 1) == '_' && phrase.charAt(i + 2) == '|') {
finished += 'u';
i += 2;
} else
finished += c;
}
return finished;
}