Ok, so I am required to create a program that will replace a word in a string according to a string, and also given a replacement. (In this case replace UK with United Kingdom)
Below is my code, but it doesn't work
import java.util.*;
public class replace
{
public static void main(String[]args){
replace("The UK should not be written as uk", "UK", "United Kingdom");
}
static void replace(String input, String seed, String replacement){
String s = "";
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length();i++){
if(input.charAt(i) != ' '){
s = s + input.charAt(i);
}
if(input.charAt(i) == ' ' || i+1 == input.length()){
bla.add(s);
s = "";
}
}
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
for(int i = 0; i < bla.size(); i++){
out = out + bla.get(i)+ " ";
}
System.out.println(out);
}
}
For some reason it's not replacing my variable with the replacement
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
Any ideas why this might be?
Thanks in advance
Replace:
if(bla.get(i) == seed)
With:
if(bla.get(i).equals(seed))
The first compares reference, the second equality.
You should also use a StringBuilder to concatanate Strings, and keep it inside the loop:
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length(); i++) {
StringBuilder s = new StringBuilder();
if(input.charAt(i) != ' ')
s.append(input.charAt(i));
if(input.charAt(i) == ' ' || i+1 == input.length())
bla.add(s.toString());
}
Using a StringBuilder is more efficient.
Related
import java.util.Scanner;
public class Chupapi {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String str = "";
System.out.print("Enter string: ");
str = input.nextLine();
getConsonantCount(str);
}
public static void getConsonantCount(String str) {
char string[] = str.toCharArray();
System.out.print("Duplicate characters in a given string: ");
for(int i = 0, count = 0; i <string.length; i++) {
count = 1;
for(int j = i+1; j <string.length; j++) {
if(string[i] == string[j] && string[i] != ' ') {
count++;
string[j] = '0';
}
}
if(count > 1 && string[i] != '0')
System.out.print(string[i]);
}
}
}
I wanted to sort out the "Duplicate characters in a given string: " output like in an alphabetical order example is,
"Duplicate characters in a given string: heuro"
I want it to be
"Duplicate characters in a given string: ehoru"
That's preatty much all that I want to do with this code, any tips on what should I do or use?
Use Arrays.sort() to sort the array before finding duplicate characters.
public static void getConsonantCount(String str)
{
char string[] = str.toCharArray();
Arrays.sort(string);
System.out.print("Duplicate characters in a given string: ");
for (int i = 0, count = 0; i < string.length; i++)
{
count = 1;
for (int j = i + 1; j < string.length; j++)
{
if (string[i] == string[j] && string[i] != ' ')
{
count++;
string[j] = '0';
}
}
if (count > 1 && string[i] != '0')
System.out.print(string[i]);
}
}
only allow charAt method and length method . Thank you so much!
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(3) == ',') {
what should i write here ? ?
}
Your code needs some refactoring, try this:
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int cutStringIndex;
if (str.charAt(i) == ',') {
cutStringIndex = i;
}
for (int i = 0; i < cutStringIndex(); i++) {
String cutStringOne = "";
cutStringOne = cutStringOne + str.charAt(i);
}
for (int i = cutStringIndex() + 1; i < str.length(); i++) {
String cutStringTwo = "";
cutStringTwo = cutStringTwo + str.charAt(i);
}
cutString = cutStringOne + " " + cutStringTwo;
return cutString;
}
This will take out the comma which appears to be what you were looking for. I only used the two methods you asked for. Essentially this code gets the index of the comma, then reconstructs the two parts of the strings until it reaches the point of the comma, and skips over it. It may need some minor tweaks for your situation but this should be what you're looking for.
It can be done like this, Suppose String s="200,300,450,600" and you have to split given string using charAt() and string.length() method then first add ',' at the end of the string as given in the code below.
String s="200,300,450,600,",str="";
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch!=','){ //checking if particular character is not ','
str+=ch; //storing it in str string
}
else{
System.out.println(str); //printing each string before ',' is found
str="";
}
}
The output of above code will be:200
300
450
600(all the numbers will be printed on next line)
If you want to use only charAt and string.length() then you should try this
void runApp{
String str = "345, 688, 123";
String values[] = strCut(str); //values[0] = 345, values[1] = 688, values[2] = 123
for(String value : values){
System.out.print(value + " ");
}
}
String[] strCut(String str) {
int elements = 1;
int index = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ',')
elements++;
}
String result[] = new String[elements];
for(int i = 0; i < result.length; i++)
result[i] = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ',') {
if(str.charAt(i) != ' ')
result[index] = result[index] + str.charAt(i);
}
else index++;
}
return result;
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
// Test
runApp();
}
static void runApp() {
String str = "345, 688"; // Expected->"345" "688"
String value = strCut(str);
System.out.println(value);// Display the result
}
static String strCut(String str) {
// Initialise result with a "
String result = "\"";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {// Check char at the index, i
// Add " at the end of one number and again " at the start of the next
result += "\" \"";
} else if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
// Add " at the end
result += "\"";
// Finally, return result
return result;
}
}
Output:
"345" "688"
if you must want to make use of charAt() then do like below..
ArrayList<String> stringArr= new ArrayList<String>();
int startindex=0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
String partString = str.substring(startindex, i) ;
startindex=i+1;
stringArr.add(partString);
}
}
String lastString = str.substring(startindex, str.length()) ;
stringArr.add(lastString);
OR
You can simply use split method like below
String[] parts = string.split(",");
String part1 = parts[0]; // 345
String part2 = parts[1]; // 688
You can achieve it by simply doing this,
This will give you the desired result.
String str = "345,688";
ArrayList<String> stringArray = new ArrayList<>();
int startindex=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ',') {
String subStr = str.substring(startindex, i);
startindex = i+1;
stringArray.add(subStr);
}
}
stringArray.add(str.substring(startindex));
I am trying to make a hangman game with String methods, however, I am having trouble replacing the "-" with the correct letter guessed, the specifications on my problem says that I need to concatenate the dashes with the letters that were guessed correctly.
this is the code I have so far for the method that checks if the letter is in the word
public static String reveal(String word, String guess)
{
String dashprints = "-", wholeword=" ";
for (int index=0; index<= word.length();index++)
{
if(index==word.indexOf(letters))
{
return dashprints;
}
else
{
dashprints=letters;
}
wholeword= dashprints+ wholeword;
}
return wholeword;
The word in the game is:
graphics
and the initial output is this:
"---------"
and the wanted output is:
"g-------"
however, the output I am getting right now is just this:
"-"
Hope this will work for you.
public static String reveal(String word, String guess) {
char[] guessChars = guess.toCharArray();
ArrayList<Character> missedChars = new ArrayList<Character>();
char[] out = new char[word.length()];
for (int i = 0; i < out.length; i++) {
out[i] = '_';
}
if (word.length() == guess.length()) {
for (int index = 0; index < word.length(); index++) {
int sts = word.indexOf(guessChars[index]);
if (sts != -1)
out[sts] = guessChars[index];
else
missedChars.add(guessChars[index]);
}
}
System.out.println("Missed Character: " + missedChars.toString());
return new String(out);
}
You can change out[i] = '_'; to out[i] = '-';
I am looking to implement a method to perform basic string compression in the form of:
aabcccccaaa -> a2b1c5a3
I have this program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(compress(str));
}
public static String compress(String str) {
char[] chars = str.toCharArray();
int count = 0;
String result = "";
for (int i = 0; i < chars.length; i++) {
char curr = chars[i];
result += curr;
for (int j = i; j < chars.length; j++) {
if (chars[j] == curr) {
count++;
}
else {
i += count;
break;
}
}
result += count;
count = 0;
}
return result;
}
}
But in my tests I am always missing the last character count.
I assume this is because the program gets out of the inner for loop before it should, but why is this the case?
Thanks a lot
You don't need two for loops for this and can do it in one go like so
String str = "aaabbbbccccca";
char[] chars = str.toCharArray();
char currentChar = str.length() > 0 ? chars[0] : ' ';
char prevChar = ' ';
int count = 1;
StringBuilder finalString = new StringBuilder();
if(str.length() > 0)
for(int i = 1; i < chars.length; i++)
{
if(currentChar == chars[i])
{
count++;
}else{
finalString.append(currentChar + "" + count);
prevChar = currentChar;
currentChar = chars[i];
count = 1;
}
}
if(str.length() > 0 && prevChar != currentChar)
finalString.append(currentChar + "" + count);
System.out.println(finalString.toString());
Output is: a3b4c5a1 for aaabbbbccccca
Keep a track of character that you are reading and compare it with next character of the string. If it is different, reset the count.
public static void stringCompression (String compression) {
String finalCompressedString = "";
char current = '1';
int count = 0;
compression = compression + '1';
for (int i = 0; i < compression.length(); i++) {
if (compression.charAt(i) == current) {
count = count + 1;
} else {
if (current != '1')
finalCompressedString = finalCompressedString + (current + Integer.toString(count));
count = 1;
current = compression.charAt(i);
}
}
System.out.println(finalCompressedString);
}
My answer for String Compression in java.
In this what i have done is and what you should have done is that , Keep a record of the characters that that are coming for a specific number of times, do so by comparing the current character with the next character , and when the current and the next character become unequal reset the value of count and repeat the whole process again for the next different character.
Hope it helps!
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for (int i=0; i<str.length(); ++i) {
int j=i+1;
count=1;
while (j!=str.length() && str.charAt(i) == str.charAt(j)) {
count += 1;
j += 1;
i += 1;
}
System.out.print(str.charAt(i));
if (count > 1) {
System.out.print(count);
}
}
}
}
i have problem writing java code to remove repeated letters from word.This code will remove repeated letter by accepting only one of the letter which is repeating . Suppose, if input is "SUSHIL" then output would be "SUHIL".
This java code i write.
import java.io.*;
import java.util.*;
public class Repeat
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
char ch1, ch2;
int i, j;
int l = name.length();
String result = "";
for (i = 0; i < l; i++)
{
for (j = 1; j < l; j++)
{
ch1 = name.charAt(i);
ch2 = name.charAt(j);
if (ch1 != ch2)
{
result = result + ch1;
break;
}
}
}
System.out.println("Output:" + result);
}
}
try this:
private static String removeRepeat(String input){
Set<Character> str = new LinkedHashSet<Character>();
for(int n=0;n<input.length();n++){
str.add(input.charAt(n));
}
return str.toString();
}
good point from the comment, changed to LinkedHashSet.
It may be the crap code, but what I mean is don't reinvent the wheel, only if you have to
char ch1,ch2;
int l=name.length();
String result="";
for(int i=0;i<l;i++){
if(name.indexOf(name.charAt(i))==i){
result+=name.charAt(i);
}
}
System.out.println(result);
input = SUSHSILHI
output = SUHIL
You should do the opposite: add the first letter to result, then check if the next letter is already in result:
boolean exist=false;
result=name.charAt(0);
for (i=1; i<l;i++) {
exist=false;
int j=0;
while (exist=false && j<i) {
if(name.charAt(i)==charAt(j)) {
exist=true;
}
j++;
}
if(exist==false){
result=result+name.charAt(i);
}
}
The for checks for all the string name, then the while checks for the characters already in result, if it doesn't already exist, else it doesn't do anything.
Using indexOf() , one for loop should work, like below
String name="SUSHIL";
String newName="";
int i=0;
int l=name.length();
for(i=0;i<l;i++)
{
char ch1=name.charAt(i);
if(!(newName.indexOf(ch1)>-1))
{
newName=newName + ch1;
}
}
System.out.println("Output:"+newName);
String name = "SUSHIL";
char ch1 = 0, ch2;
int i, j;
int l = name.length();
StringBuilder sb = new StringBuilder();
for (i = 0; i < l; i++)
{
//this is used to append char to StringBuilder
boolean shouldAppend = true;
//if we don't check if the length is equal to 0 to start then the below loop will never run and the result would be an empty string so just append the first character to the StringBuilder
if (sb.length() == 0)
{
sb.append(name.charAt(i));
shouldAppend = false;
}
else
{
for (j = 0; j < sb.length(); j++)
{
ch1 = name.charAt(i);
ch2 = sb.charAt(j);
if (ch1 == ch2)
{
//StringBuilder contains ch1 so turn shouldAppend to false and break out of this inner loop
shouldAppend = false;
break;
}
}
}
if (shouldAppend) sb.append(ch1);
}
System.out.println("Output:" + sb.toString());
Try:
//Globally
List<Character> list = new ArrayList<Character>();
public String remRepeats(String original)
{
char ch = original.charAt(0);
if (original.length() == 1)
return original;
if (list.contains(ch))
return remRepeats(original.substring(1));
else
{
list.add(ch);
return ch + remRepeats(original.substring(1));
}
}
List<Character> characters = new ArrayList<>();
char[] chars = name.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for(char currChar:chars) {
if (!characters.contains(currChar)) {
characters.add(currChar);
stringBuilder.append(currChar);
}
}
System.out.println(stringBuilder);