I know this question was asked many times, but I didn't find any of the answers helpful in my case. I have a method that receives a String. I want to check if any of the characters in the string are repeated. If so the method will return an empty String. If not it will return the String back.
The method is looking for any repeated character in the String.
private String visit(String word) {
int count = 0;
if(word == ""){
return "<empty>";
}
//alphabet is an array that holds all characters that could be used in the String
for(int i = 0; i < alphabet.length; i++){
for(int j = 0; j < word.length(); j++){
if(alphabet[i] == word.charAt(j)){
count++;
}
if(count == 2){
return "";
}
}
count = 0;
}
return word;
}
Ok, I publish my solution to this:
package main;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
System.out.println(hasDups("abc"));
System.out.println(hasDups("abcb"));
}
public static String hasDups(String arg) {
String[] ar = arg.split("");
Arrays.sort(ar);
boolean noDups = true;
for (int i = 1; i < ar.length && noDups; i++) {
if (ar[i].equals(ar[i-1])) noDups = false;
}
if (noDups) return arg; else return "";
}
}
This might not be the best way of doing what you want, but you can use two for loops to check each character against all the other characters to see if it is repeated.
public static String hasRepeated(String word) {
if (word.isEmpty()) return "<empty>";
char[] charArray = word.toCharArray();
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
if (i == j) {
} else if (Character.toString(charArray[i]).
equalsIgnoreCase(Character.toString(charArray[j]))) {
return "";
}
}
}
return word;
}
Note: This code assumes that the case of the character doesn't matter, it just checks if it is repeated.
/**
* Returns the index of the first character repeated, or -1 if no repeats
*/
public static int firstRepeated( String s ) {
if ( s != null ) {
int n = s.length();
for (int i = 0; i < (n - 1); i++) {
int indx = s.indexOf( s.charAt( i ), i + 1 );
if ( indx > 0 ) {
return i;
}
}
}
return -1;
}
This works!!
public static String checkDuplicate(String str)
{
int count = 0;
char[] charArray = str.toCharArray();
for(int i=0;i<charArray.length;i++)
{
count = 0;
for(int j=0;j<charArray.length;j++)
{
if(charArray[i]==charArray[j])
{
count++;
if(count==2) break;
}
}
if(count==2) break;
}
if(count==2)
return "";
else
return str;
}
}
Related
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);
}
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"));
}
}
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"));
}
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);
I want to shift each i in a given string one index to the right. How can I do that? For example:
"Chit Nyein Oo is nothing.";
becomes
"Chti Nyeni Oo si nothnig.";
If i occurs in the last index, it need not change its position.
Use string.replaceAll
string.replaceAll("i(.)", "$1i");
DEMO
EDIT: NOW it works for all conditions. Last letter in the String is 'i' or not, it works.
public class t4 {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothing.";
char o = 'i';
int indexes = 0;
if(input.charAt(input.length()-1) != 'i'){ //Test if last letter is not 'i'
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
System.out.println(input);
System.out.println(swappedString);
} else { //so last letter is i
char t = input.charAt(input.length()-1);
String ha = input.substring(0, input.length()-1);
input = ha;
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
swappedString = swappedString + Character.toString(t);
System.out.println(input);
System.out.println(swappedString);
}
}
}
You can do this using a StringBuilder.
class Test {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothingi";
int len = input.length();
StringBuilder sb = new StringBuilder();
// System.out.println(sb);
for(int i=0; i<len; i++) {
char charAti = input.charAt(i);
if(charAti == 'i' && i<len-1) {
sb.append(input.charAt(i+1));
sb.append(charAti);
i++;
}
else {
sb.append(charAti);
}
}
System.out.println(sb);
}
}
I am attempting to solve a codingbat problem called mirrorEnds. My solution fails but I'm not getting any useful feedback from the site, only a failed test run:
And my code (I changed string to str cause I'm used to the problems with "str"):
public String mirrorEnds(String string) {
String str = string;
StringBuilder sb = new StringBuilder();
int beg = 0;
int end = str.length()-1;
while(beg < end)
{
if(str.charAt(beg)==str.charAt(end))
sb.append(str.substring(beg,beg+1));
else
break;
++beg;
--end;
}
if(beg==end)
return str;
else
return sb.toString();
}
Here's mine, for what it's worth (not much, I know, but I was writing it while you were finding the bug..)
private String mirrorEnds(String string) {
final char[] chars = string.toCharArray();
final int n = chars.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (chars[i] != chars[n - i - 1])
break;
sb.append(chars[i]);
}
return sb.toString();
}
Bah. I found it. Instance is "abba"
Needed to change "if(beg==end)" to "if(beg>=end)".
public String mirrorEnds(String string) {
String s = "";
String str = "";
for (int i=string.length()-1; i>=0; i--)
{
s = s + string.charAt(i);
}
for (int j=0; j<string.length(); j++)
{
if (s.charAt(j) == string.charAt(j))
{
str = str + string.charAt(j);
}
if (s.charAt(j) != string.charAt(j))
{
break;
}
}
return str;
}
public static String mirrorEnds(String string) {
for (int i = 0; i < string.length(); i++) {
if(string.charAt(i) != string.charAt(string.length()-i-1)){
return string.substring(0,i);
}
else if(i==string.length()-1) return string;
}
return "";
}
Making a helper method is both efficient and makes the job easier, and logic clearer, recommended strategy for beginners, dissect the logic out, then put it together, as seen in codingBat's fizzBuzz questions that build up to the real fizzBuzz. Even though there a shorter solutions, this shows the full extent of logic used.
public String mirrorEnds(String string) {
String reversed = reverseString(string); //the reversed version
String result = "";
for(int a = 0; a < string.length(); a++){
if(string.charAt(a) == reversed.charAt(a)){ //keep going...
result += string.charAt(a);
}
else if(string.charAt(a) != reversed.charAt(a)){
break; //error, stop
}
}
return result;
}
public String reverseString(String s){
String reversed = "";
for(int a = s.length() - 1; a >= 0; a--){
reversed += s.charAt(a);
}
return reversed;
}
Here is mine:
public String mirrorEnds(String str) {
String res = "";
int count = str.length() - 1;
for(int i = 0;i < str.length();i++)
{
if(str.charAt(i) == str.charAt(count))
res += str.substring(i, i + 1);
else
break;
count--;
}
return res;
}
Here's my solution, hope it can help you
public String mirrorEnds(String string) {
int mid = string.length() / 2;
String s = "";
for (int i = 0, j = string.length()-1; i <= mid; i++, j--) {
if (i == mid) {
return string;
}
if (string.charAt(i) == string.charAt(j)) {
s += string.charAt(i) + "";
} else {
break;
}
}
return s;
}
Here's mine. I did mine a little bit different.
public String mirrorEnds(String string) {
//Create a string that we will eventually return.
String ret = "";
//Create a for loop that takes in chars from both ends.
for (int i = 0; i < string.length(); i++)
{
//Create one and two characters in order to simplify it.
char one = string.charAt(i);
char two = string.charAt(string.length() - 1 - i);
//If the front and back character in the iteration
//equal each other, then we add the character to the return string.
if (one == two)
{
ret = ret + one;
}
//Otherwise, we end the loop because we don't want to
//Have a loopback problem.
else
{
break;
}
}
//Return the string that we are working on.
return ret;
}
Given a string how can i figure out the number of times each char in a string repeats itself
ex: aaaabbaaDD
output: 4a2b2a2D
public static void Calc() {
Input();
int count = 1;
String compressed = "";
for (int i = 0; i < input.length(); i++) {
if (lastChar == input.charAt(i)) {
count++;
compressed += Integer.toString(count) + input.charAt(i);
}
else {
lastChar = input.charAt(i);
count = 1;
}
}
System.out.println(compressed);
}
What you'r looking for is "Run-length encoding". Here is the working code to do that;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
// iterate through input string
// Iterate the string N no.of.times where N is size of the string to find run length for each character
for (int i = 0; i < source.length(); i++) {
// By default run Length for all character is one
int runLength = 1;
// Loop condition will break when it finds next character is different from previous character.
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance.
This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.
import java.io.*;
public class RunLength {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
System.out.println("Please enter the string");
String str = br.readLine();//the input string is in str
calculateFrequency(str);
}
private static void calculateFrequency(String str) {
int length = str.length();
String characters[] = new String[length];//to store all unique characters in string
int frequency[] = new int[length];//to store the frequency of the characters
for (int i = 0; i < length; i++) {
characters[i] = null;
frequency[i] = 0;
}
//To get unique characters
char temp;
String temporary;
int uniqueCount = 0;
for (int i = 0; i < length; i++) {
int flag = 0;
temp = str.charAt(i);
temporary = "" + temp;
for (int j = 0; j < length; j++) {
if (characters[j] != null && characters[j].equals(temporary)) {
flag = 1;
break;
}
}
if (flag == 0) {
characters[uniqueCount] = temporary;
uniqueCount++;
}
}
// To get the frequency of the characters
for(int i=0;i<length;i++){
temp=str.charAt(i);
temporary = ""+temp;
for(int j=0;i<characters.length;j++){
if(characters[j].equals(temporary)){
frequency[j]++;
break;
}
}
}
// To display the output
for (int i = 0; i < length; i++) {
if (characters[i] != null) {
System.out.println(characters[i]+" "+frequency[i]);
}
}
}}
Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.
#Balarmurugan k's solution is better - but just by improving upon your code I came up with this -
String input = "aaaabbaaDD";
int count = 0;
char lastChar = 0;
int inputSize = input.length();
String output = "";
for (int i = 0; i < inputSize; i++) {
if (i == 0) {
lastChar = input.charAt(i);
count++;
} else {
if (lastChar == input.charAt(i)) {
count++;
} else {
output = output + count + "" + lastChar;
count = 1;
lastChar = input.charAt(i);
}
}
}
output = output + count + "" + lastChar;
System.out.println(output);