Java method to replace a letter with another - java

I need help to do my exercises. I want to replace letters ā€˜aā€™ with an ā€˜eā€™ in a phrase. For the input: "are you angry" the output should be: "ere you engry".
I tried this but I can't fix it.
public static void main (String [] args){
String s= "are you angry";
remplaceLettre(s);
}
public static void remplaceLettre(String s){
char converted = 0;
String w = "e";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) =='a') {
converted = Character.toUpperCase(s.charAt(i));
w = s.replace(s.charAt(i), converted);
s = w;
} else {
converted = Character.toUpperCase(s.charAt(i));
w = s.replace(s.charAt(i), converted);
s = w;
}
}
System.out.println(s);
}
}
output : "are you angry"
Expected output : "ere you engry"

You can use String.replace method like this:
public static void remplaceLettre(String s){
System.out.println(s.replace("a", "e"));
}
If you must use case insensitive replace try this:
s.replaceAll("(?i)a", "e")

package com.khan.vaquar;
public class Test {
public static void main(String[] args) {
String str = "are you angry";
char replaceWith = 'e';
int index[] = { 0, 8 }; //here you can add index want to replace
replaceLettre(str, replaceWith, index);
}
public static String replaceLettre(String str, char ch, int[] index) {
if (null == str) {
return str;
}
char[] chars = str.toCharArray();
for (int i = 0; i < index.length; i++) {
chars[index[i]] = ch;
}
System.out.println(String.valueOf(chars));
return String.valueOf(chars);
}
}
Output : ere you engry

Related

Attempting to make altcase. Char is derefferenced, how do I fix this?

I'm trying to make altcase.
Most of the program works except where I ad the strings together on both the if and else statement. (where newstr = newstr....)
If this were to run, it should output
'I HoPe aLtCaSe wOrKs'
public class tester {
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text)
{
int COUNT = text.length();
char c;
int check = 0;
String newstr = "";
for (int i = 0; i < COUNT; i++)
{
c = text.charAt(i);
if(check == 0) {
c = c.toUpperCase();
newstr = newstr + c;
check++;
}
else {
c = c.toLowerCase();
newstr = newstr + c;
check--;
}
}
return newstr;
}
}
The code should be like this
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text)
{
int COUNT = text.length();
char c;
int check = 0;
String newstr = "";
for (int i = 0; i < COUNT; i++)
{
c = text.charAt(i);
if(c==' ') {
newstr = newstr + c;
continue;
}
if(check == 0) {
c = (char)(c-32);
newstr = newstr + c;
check++;
}
else {
newstr = newstr + c;
check--;
}
}
return newstr;
}
If you need a solution without using toUpperCase() or toLowerCase(), I suggest you to try this out.
public class Tester {
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text) {
char[] array = text.toCharArray();
text ="";
for (int i = 0; i < array.length; i++) {
text += (i%2!=0)?array[i]:Tester.utilityToUpper(array[i]);
}
return text;
}
public static char utilityToUpper(char i){
return (char) ((i!=' ')? (i - 32) : i);
}
}
I would call String.toCharArray() and then convert even indices to uppercase with Character.toUpperCase(char) and odd indices to lowercase with Character.toLowerCase(char). Finally, return a new String based on the updated char[]. Like,
public static String altCase(String text) {
char[] arr = text.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
arr[i] = Character.toUpperCase(arr[i]);
} else {
arr[i] = Character.toLowerCase(arr[i]);
}
}
return new String(arr);
}
On reflection, we can improve that by converting the input to upper case first, and then only changing odd elements to lower-case. Like,
public static String altCase(String text) {
char[] arr = text.toUpperCase().toCharArray();
for (int i = 1; i < arr.length; i += 2) {
arr[i] = Character.toLowerCase(arr[i]);
}
return new String(arr);
}
I'm assuming input isn't always strictly lower-case. If it is, then it would be trivial to skip the up-front case conversion and apply the same approach to the even indices. Like,
public static String altCase(String text) {
char[] arr = text.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
arr[i] = Character.toUpperCase(arr[i]);
}
return new String(arr);
}

Java How do I merge all char from an array of String into a new String?

I'm making a method
public static String merge(String... s)
This is the input:
String a = merge("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
System.out.println(a);
Expected Output:
ALGORITMER OG DATASTRUKTURER
I try to run a loop many times so that it picks up s[0].charAt(index) and appends it to a string for output. The problem I run into is that when I try to run the loop for s[1].charAt(1) it's null, I want it to not get StringIndexOutOfBoundsException, and instead continue to s[2] and appends s[2].char to the String.
How do I go about that?
You need to check the length of each String before trying to access its i'th character :
StringBuilder sb = new StringBuilder();
int index = 0;
boolean maxLengthReached = false;
while (!maxLengthReached) {
maxLengthReached = true;
for (String str : input) {
if (index < str.length) {
sb.append(str.charAt(index));
maxLengthReached = false;
}
}
index++;
}
return sb.toString();
Just to clarify, I'm using a boolean maxLengthReached to determine when the last character of the longest String is appended to the output. If in a full iteration over all the Strings in the input array we don't find any String long enough to have charAt(index), we know we are done.
First you need a method to get the longest String, something like -
private static String getLongestString(String... arr) {
String str = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() > str.length()) {
str = arr[i];
}
}
return str;
}
Then you can write a nested loop in your merge(), something like -
public static String merge(String... stringArray) {
StringBuilder sb = new StringBuilder();
int pos = 0;
int len = getLongestString(stringArray).length();
while (pos < len) {
for (String str : stringArray) {
if (str.length() > pos) {
sb.append(str.charAt(pos));
}
}
pos++;
}
return sb.toString();
}
Then you can call it -
public static void main(String[] args) {
String a = merge("AM ", "L", "GEDS", "ORATKRR", "", "R TRTE", "IO",
"TGAUU");
System.out.println(a);
}
Output is (the requested) -
ALGORITMER OG DATASTRUKTURER
The following code does what you need. It works for any number of strings because it uses the varargs (three dots) that allow you to pass any number of strings into merge
Use the getLongest() to find the length of the longest string.
static int getLongest(String... strings) {
int len = 0;
for(String str : strings) {
if(str.length() > len) {
len = str.length();
}
}
return len;
}
Then you merge all the i-th character from each String into a StringBuilder.
static String merge(String ...strings) {
int longest = getLongest(strings);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < longest; i++) {
for(String str : strings) {
if(i < str.length()) {
sb.append(str.charAt(i));
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String a = merge("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
System.out.println(a);
}
Output
ALGORITMER OG DATASTRUKTURER

Remove repeated characters in a string

I need to write a static method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a String, it returns "make".
I already tried the following code, but it doesn't seem to display the last character.
Here's my code:
import java.util.Scanner;
public class undouble {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("enter String: ");
String str = console.nextLine();
System.out.println(removeSpaces(str));
}
public static String removeSpaces(String str){
String ourString="";
int j = 0;
for (int i=0; i<str.length()-1 ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
return ourString;
}
}
You could use regular expressions for that.
For instance:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));
Output:
done
Pattern explanation:
"(.)\\1{1,}" means any character (added to group 1) followed by itself at least once
"$1" references contents of group 1
maybe:
for (int i=1; i<str.length() ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:
EDIT:
public void removeSpaces(String str){
String ourString="";
for (int i=0; i<str.length()-1 ; i++){
if(i==0){
ourString = ""+str.charAt(i);
}else{
if(str.charAt(i-1) != str.charAt(i)){
ourString = ourString +str.charAt(i);
}
}
}
System.out.println(ourString);
}
if you cannot use replace or replaceAll, here is an alternative. O(2n), O(N) for stockage and O(N) for creating the string. It removes all repeated chars in the string put them in a stringbuilder.
input : abcdef , output : abcdef
input : aabbcdeef, output : cdf
private static String remove_repeated_char(String str)
{
StringBuilder result = new StringBuilder();
HashMap<Character, Integer> items = new HashMap<>();
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == null)
items.put(current, 1);
else
items.put(current, ocurrence + 1);
}
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == 1)
result.append(current);
}
return result.toString();
}
import java.util.*;
public class string2 {
public static void main(String[] args) {
//removes repeat character from array
Scanner sc=new Scanner(System.in);
StringBuffer sf=new StringBuffer();
System.out.println("enter a string");
sf.append(sc.nextLine());
System.out.println("string="+sf);
int i=0;
while( i<sf.length())
{
int j=1+i;
while(j<sf.length())
{
if(sf.charAt(i)==sf.charAt(j))
{
sf.deleteCharAt(j);
}
else
{
j=j+1;
}
}
i=i+1;
}
System.out.println("string="+sf);
}
}
Input AABBBccDDD, Output BD
Input ABBCDDA, Outout C
private String reducedString(String s){
char[] arr = s.toCharArray();
String newString = "";
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put(arr[0],1);
for(int index=1;index<s.length();index++)
{
Character key = arr[index];
int value;
if(map.get(key) ==null)
{
value =0;
}
else
{
value = map.get(key);
}
value = value+1;
map.put(key,value);
}
Set<Character> keyset = map.keySet();
for(Character c: keyset)
{
int value = map.get(c);
if(value%2 !=0)
{
newString+=c;
}
}
newString = newString.equals("")?"Empty String":newString;
return newString;
}
public class RemoveDuplicateCharecterInString {
static String input = new String("abbbbbbbbbbbbbbbbccccd");
static String output = "";
public static void main(String[] args)
{
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
char temp = input.charAt(i);
boolean check = false;
for (int j = 0; j < output.length(); j++) {
if (output.charAt(j) == input.charAt(i)) {
check = true;
}
}
if (!check) {
output = output + input.charAt(i);
}
}
System.out.println(" " + output);
}
}
Answer : abcd
public class RepeatedChar {
public static void main(String[] args) {
String rS = "maaaakkee";
String outCome= rS.charAt(0)+"";
int count =0;
char [] cA =rS.toCharArray();
for(int i =0; i+1<cA.length; ++i) {
if(rS.charAt(i) != rS.charAt(i+1)) {
outCome += rS.charAt(i+1);
}
}
System.out.println(outCome);
}
}
TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS:
package replace;
public class removingrepeatedcharacters
{
public static void main(String...args){
int i,j=0,count=0;
String str="noordeen";
String str2="noordeen";
char[] ch=str.toCharArray();
for(i=0;i<=5;i++)
{
count=0;
for(j=0;j<str2.length();j++)
{
if(ch[i]==str2.charAt(j))
{
count++;
System.out.println("at the index "+j +"position "+ch[i]+ "+ count is"+count);
if(count>=2){
str=str2;
str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
}
System.out.println("after replacing " +str2);
}
}
}
}
}
String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
outstr = outstr + str.charAt(i);
}
outstring = outstr + str.charAt(i);
}
System.out.println(outstring);
public static void remove_duplicates(String str){
String outstr="";
String outstring="";
for(int i=0;i<str.length()-1;i++) {
if(str.charAt(i)!=str.charAt(i+1)) {
outstr=outstr+str.charAt(i);
}
outstring=outstr+str.charAt(i);
}
System.out.println(outstring);
}
More fun with java 7:
System.out.println("11223344445555".replaceAll("(?<nums>.+)\\k<nums>+","${nums}"));
No more cryptic numbers in regexes.
public static String removeDuplicates(String str) {
String str2 = "" + str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i) && i != 0) {
continue;
}
str2 = str2 + str.charAt(i);
}
return str2;
}

for loop to find consonants in a string

Using a for loop, how do I go about making all consonants in a string uppercase?
I think I should do something like this:
String str = "fish$"
String strConsonants = "f, s, h";
for (int x = 0; x < str.length(); x++)
{
if(((str.charAt(x) == (strConsonants))
{
System.out.print("FiSH$");
}
}
use String.contains() method from String API. the followingcode would work for your present input. usually, if you want to find all the consonents, have an char[] of consonents or String with all the consonents and do the check.
String str = "fish$";
String strConsonants = "f, s, h";
String temp="";
for (int x = 0; x < str.length(); x++){
temp+= str.charAt(x);
if(!strConsonants.contains(temp)) {
consonentsUCase+=temp.toUpperCase();
}
temp="";
}
I've just written it.
Output: FiSH$
Works for any word ! ;)
API method: printStringWithUpperConsonant
import java.util.HashSet;
import java.util.Set;
public class ConsonantUtils {
private Set<Character> vowels = getVowels();
private String analysedString;
public ConsonantUtils(String analysedString) {
this.analysedString = analysedString;
}
public static void main(String[] args) {
new ConsonantUtils("fish$").printStringWithUpperConsonant();
}
public void printStringWithUpperConsonant() {
for (int i = 0; i < getAnalysedString().length(); i++) {
printChar(getCurrentChar(i));
}
}
private char getCurrentChar(int i) {
return getAnalysedString().charAt(i);
}
private void printChar(char currentChar) {
if (isConsonant(currentChar)) {
System.out.print(makeCharUpperCase(currentChar));
}
else{
System.out.print(currentChar);
}
}
private Set<Character> getVowels() {
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
return vowels;
}
private char makeCharUpperCase(char character) {
return Character.toUpperCase(character);
}
private boolean isConsonant(char currentChar) {
return !vowels.contains(currentChar);
}
private String getAnalysedString(){
return analysedString;
}
}
You can use Character.toUpperCase().
String vowels = "aeiouAEIOU";
char[] charArr = str.toCharArray(); //turn the string into char array
for(int i=0; i<charArr.length; i++) { //for loop
if(vowels.indexOf(charArr[i]) == -1) { // if not a vowel
charArr[i] = Character.toUpperCase(charArr[i]); //replace with upper case
}
}
Sting rslt = String.valueOf(charArr); //finally turn the array back to string
String str = "fish$";
String strVowels = "aeiouAEIOU";
String out = "";
for (Character c : str.toCharArray())
{
if(!strVowels.contains(""+c))
{
out = out + Character.toUpperCase(c);
}
else
{
out = out + c;
}
}
System.out.println(out);
This works for me:
List<Character> constants = Arrays.asList('f', 's', 'h');
String str = "fish$";
for (Character c : constants) {
str = str.replace(c, Character.toUpperCase(c));
}

replacing a character every occurrence in a string in java

I'm suppose to replace a "L" in a string every time it is found in the string HELLO WORLD, with "x". and the x is to increased every occurrence of L.
input: "HELLO WORLD"
output: "HExxxO WORxxxD"
use only String methods: .length; .indexOf; .substring
and .concat (or +).
EDIT
Here's my try:
public static String replace(String input,String pattern) {
String result = " ";
int stringLength;
int patternIndex;
while (input !=null) {
patternIndex = input.indexOf(pattern);
stringLength = input.length();
}
return result;
}
i only find the index of the pattern and the length of the string having problem with replacing the character.
First: sane solution:
StringBuilder sb = new StringBuilder();
StringBuilder r = new StringBuilder();
for( char c : "HELLO LAZY LIMBO WORLD" .toCharArray() ) {
if( c == 'L' ) {
sb.append(r.append('x'));
} else {
sb.append( c );
}
}
return sb.toString() );
Then modified to meed the criteria of only using valid methods .length; .indexOf; .substring and .concat (or +) ( removing toCharArray(); and StringBuilder )
public static String replace( String input ){
String replacement = "";
int iot = -1;
while( ( iot = input.indexOf('L')) > -1 ) {
input = input.substring(0,iot) +
( replacement+='x' ) +
input.substring(iot+1);
}
return input;
}
That one look like a for loop. Let's change it!
With only two statements ( declr and a for loop ):
public static String replace( String in ){
String x = "";
for( int i = 0; ( i = in.indexOf('L',i)) > -1 ;
in = in.substring(0,i++) + ( x=x+'x' ) + in.substring(i) );
return in;
}
Yields:
HExxxO xxxAZY xxxxIMBO WOxxxxxR
Now, that's! a for loop. I almost make Java look like perl.
static String xform(String helloWorld) {
if (helloWorld.intern() != "HELLO WORLD")
throw new IllegalArgumentException("bad World");
return "HExxxO WORxxxD";
}
and here is a very special version for the ones w/o sense of humor: the special edition - loplez&funless
public class TheLoop {
public static void main(String[] args) throws Throwable{
System.out.println(xForm2("Hello World -L".toUpperCase(),0));
}
static String xForm2(String s,int k){
return k<-1?"x"+xForm2(s,k+1):(k==-1?"":("L".equals(s.substring(0,1))?xForm2(s,-(k+1)-1) :s.substring(0,1))+(s.length()==1?"":xForm2(s.substring(1), "L".equals(s.substring(0,1))?k+1:k)));
}
}
200 bounty if anyone manages to write the function in a single line (single semicolon) and uglier than this
String x_ify(String input) {
String output = "";
int start = 0;
int count = 0;
int nextL;
while ((nextL = input.indexOf('L', start)) >= 0) {
if (nextL > start) {
output = output + input.substring(start, nextL);
}
++count;
for (int i = 0; i < count; ++i) {
output = output + "x";
}
start = nextL + 1;
}
if (start < input.length()) {
output += input.substring(start);
}
return output;
}
char charToReplace = 'l';
String str = " Hello World";
char newChar = 'x';
String newString = "x";
StringBuilder result = new StringBuilder();
for (int index = 0; index < str.length(); index++) {
if (str.charAt(index) == charToReplace) {
result.append(newString);
newString += newChar;
} else {
result.append(str.charAt(index));
}
}
System.out.println(result);
Note: it can be optimized
A bodyless one-liner for statement, specially for bestsss:
public static String replace(String s) {
for (String x=""; s.indexOf('L') > -1 ; s = s.substring(0,s.indexOf('L')) + ( x=x+'x' ) + s.substring(s.indexOf('L')+1) );
return s;
}
Although not using the standard functions you mentioned but this is an alternate way:
public static void first()
{
String input = "HELLO WORLD";
String X = "";
int numofL = input.length() - input.replaceAll("L+", "").length();
for(int i=0;i<numofL;i++)
X += "x";
String output = input.replaceAll("L+", X);
System.out.println(output);
}
public static void main(String[] args) {
String input = "HELLO WORLD";
String output = "";
String repl = "x";
int idx, start = 0;
while ((idx = input.indexOf('L', start)) > 0) {
output += input.substring(start, idx);
output += repl;
start = idx + 1;
repl += "x";
}
if (start < input.length()) {
output += input.substring(start);
}
System.out.println(output);
}
public class Main {
public static void main(String[] args) {
System.out.println(replace("hello world", "x"));
}
public static String replace(String in, String xs) {
return in.indexOf("l") != -1 ? replace(in.substring(0, in.indexOf("l")) + xs + in.substring(in.indexOf("l") + 1), xs + "x") : in;
}
}
public class ReplaceChar {
public static void replaceChar(String s, StringBuilder sb, int depth){
int i = s.indexOf('L');
if(i==-1){
return;
}
else
sb.append(s.substring(0,i));
for(int j=depth;j>0;j--){
sb.append('x');
}
replaceChar(s.substring(i+1),sb,++depth);
}
public static void main(String[] args){
StringBuilder sb = new StringBuilder();
System.out.println("main "+sb);
replaceChar("HELLO WORLD",sb,1);
}
}

Categories