How to count the characters only if they are right next to each other, otherwise just print the characters as they are. I wrote the following code based on my little knowledge of Java.
for example String w="kjiikkkjial";
the result should be: kji2k3jial
String am ="asbbaamkkkjkssg";
char op = 0;
char[] ch = am.toCharArray();
for(int i=0; i<ch.length; i++) {
int k=1;
for(int j=i+1; j<ch.length; j++) {
if(ch[i]==ch[j]) {
k++;
op=ch[j];
i=j;
}
else break;
}
if(k>1)
System.out.print(op+""+k);
else
System.out.print(ch[i]);
}
This should work, call this function with the input as your string and it will return the expected output.
public static String runLengthEncoding(String text) {
String encodedString = "";
for (int i = 0, count = 1; i < text.length(); i++) {
if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1))
count++;
else {
encodedString = encodedString.concat(Character.toString(text.charAt(i)));
if(count>1) {
encodedString = encodedString.concat(Integer.toString(count));
}
count = 1;
}
}
return encodedString;
}
This is a link to the working example on ideone.
Related
I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}
I have a string "text" in one class which calls on a method in another class to convert text in various ways. In this method though I am left with an "ArrayIndexOutOfBoundsException" error.
public String toUnicode() {
char unicodeTextArray[] = new char[text.length()];
if (text == null || text.isEmpty()) {
return "";
}
String unicodeTextArrayString[] = new String[text.length()];
for (int i = 0; i < text.length(); i++) {
unicodeTextArray[i] = text.charAt(i);
if (unicodeTextArray[i] < 0x10) {
unicodeTextArrayString[i] = "\\u000" + Integer.toHexString(unicodeTextArray[i]);
} else if (unicodeTextArray[i] < 0x100) {
unicodeTextArrayString[i] = "\\u00" + Integer.toHexString(unicodeTextArray[i]);
} else if (unicodeTextArray[i] < 0x1000) {
unicodeTextArrayString[i] = "\\u0" + Integer.toHexString(unicodeTextArray[i]);
}
unicodeTextArrayString[i] = "\\u" + Integer.toHexString(unicodeTextArray[i]);
}
String unicode = unicodeTextArrayString[text.length()];
return unicode;
}
Changing one line to an arbitrarily large number such as:
String unicodeTextArrayString[] = new String[9999];
Results in no error, but it returns null.
I thought about setting an int variable to increase the length of the array, but * 4 was still too small of an array size and it seems like if I go too large it just returns null.
How could I go about getting the correct length of the array?
EDIT: I found a non-array approach that works, but I would still like to know if there is a way to make the above array approach work in some way.
public String toUnicode()
{
String unicodeString = "";
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
String s = String.format ("\\u%04x", (int)c);
unicodeString = unicodeString + s;
}
return unicodeString;
}
EDIT 2: In case anyone reading this is curious, to get the decimal value of the unicode:
public String toUnicode()
{
String unicodeString = "";
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
int unicodeDecimal = c;
unicodeString = unicodeString + unicodeDecimal + " ";
}
return unicodeString;
}
EDIT 3: I ended up deciding to use the following, which separates unicode decimals by space, and checks for the unicode value 10 (which means new line) and outputs a new line into the string instead of that value.
public String toUnicode()
{
String unicodeString = "";
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
int unicodeDecimal = c;
if (unicodeDecimal == 10)
{
unicodeString = unicodeString + "\n";
}
else
{
unicodeString = unicodeString + unicodeDecimal + " ";
}
}
return unicodeString;
}
couple of things
1) Move line
char unicodeTextArray[] = new char[text.length()]; after following code
if (text == null || text.isEmpty())
{
return "";
}
char unicodeTextArray[] = new char[text.length()];
2) Error is because of this String unicode = unicodeTextArrayString[text.length()];
e.g you get a text as "hello", then you initialized unicodeTextArrayString of size text.length() which is 5. So you can fetch back from this array for index 0 to 4 only, but you are trying to fetch from index 5, which is out of bounds.
3) After having said so, the code/logic seems wrong. I just modified your logic using StringBuilder instead. You can check for conversion logic
public static String toUnicode(String text)
{
if (text == null || text.isEmpty())
{
return "";
}
StringBuilder unicodeTextArrayString = new StringBuilder();
for (int i = 0; i < text.length(); i++)
{
char ch = text.charAt(i);
if (ch < 0x10)
{
unicodeTextArrayString.append("\\u000" + Integer.toHexString(ch));
}
else if (ch < 0x100)
{
unicodeTextArrayString.append("\\u00" + Integer.toHexString(ch));
}
else if (ch < 0x1000)
{
unicodeTextArrayString.append("\\u0" + Integer.toHexString(ch));
}
else
{
unicodeTextArrayString.append("\\u" + Integer.toHexString(ch));
}
}
return unicodeTextArrayString.toString();
}
4) If you want to use array based approach, then add each chars to arrays, and then iterate again through array where u stored chars, and then build a string (instead of getting a string from last index) and then return the string
this one is the culprit
String unicode = unicodeTextArrayString[text.length()];
edit:
If you really want to make the original code to work in some way, I think there are several ways to do it. The following code is one of them.
public String toUnicode() {
char unicodeTextArray[] = new char[text.length()];
if (text == null) {
return "";
}
String unicodeTextArrayString[] = new String[text.length()];
StringBuilder unicode= new StringBuilder();
for (int i = 0; i < text.length(); i++) {
unicodeTextArray[i] = text.charAt(i);
if (unicodeTextArray[i] < 0x10) {
unicodeTextArrayString[i] = "\\u000" + Integer.toHexString(unicodeTextArray[i]);
} else if (unicodeTextArray[i] < 0x100) {
unicodeTextArrayString[i] = "\\u00" + Integer.toHexString(unicodeTextArray[i]);
} else if (unicodeTextArray[i] < 0x1000) {
unicodeTextArrayString[i] = "\\u0" + Integer.toHexString(unicodeTextArray[i]);
} else
unicodeTextArrayString[i] = "\\u" + Integer.toHexString(unicodeTextArray[i]);
unicode = unicode.append(unicodeTextArrayString[i]);
}
return unicode.toString();
}
I was asked to replace the first 5 characters in any sentence inputted in JOptionPane, with asterisks. So I have this...
import javax.swing.*;
public class Option {
public static void main (String[] args) {
String myName;
myName= JOptionPane.showInputDialog("Input a sentence");
System.out.println(myName.substring
I just can't figure out how to isolate the first 5 characters in any sentence with spaces. Any help or hints on this would be great
You can use regex, like this:
myName = myName.replaceFirst(".{5}", "*****");
.{5} is regex and means five characters.
EDIT: Since you needed to distinguish white spaces:
String tmp;
int lastCharIndex;
while(int i < 5) {
if (!Character.isWhiteSpace(string.charAt(i)) {
tmp += *
i++;
} else {
tmp += " ";
}
lastCharIndex++;
}
tmp += myName.substring(lastCharIndex);
This solution is a bit longer but doesn't replace spaces with asterisks:
import javax.swing.*;
public class Option {
public static void main (String[] args) {
String myName;
myName= JOptionPane.showInputDialog("Input a sentence");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
if(myName.charAt(i) != " ") {
sb.append('*');
}
else sb.append(' ');
}
System.out.println(sb.toString() + myName.subString(5));
}
}
It's more simple and fast if you use a loop for replace the desired characters. e.g.:
String input = "Hey how are you";
char[] chars = input.toCharArray();
for (int i = 0, j = 0; i < chars.length && j < 5; i++) {
char ch = chars[i];
if (!Character.isWhitespace(ch)) {
chars[i] = '*';
j++;
}
}
String output = new String(chars);
System.out.println(output);
Output:
*** **w are you
Character.isWhiteSpace()
This is a good method to use
String s = "Hi I am good";
String newString = "";
int count = 0
int i = 0;
while(count < 5){
if (!Character.isWhiteSpace(s.charAt(i)) {
newString += '*';
count++;
i++;
} else {
newString += string.charAt(i);
i++;
}
}
for (int i = count; i < s.length; i++) {
newString += string.charAt(i);
}
System.out.println(newString);
// ** * ** good
You could always implement a simple for loop with a condition inside like this:
int charCount = 0;
for(int i = 0; i < myName.length(); i++){
if(myName.charAt(i) != ' '){
myName = '*" + myName.subString(i);
charCount++;
}
if(charCount == 5)
break;
}
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);