Decompressing String method - java

I need help with decompressing method. I have a working Compress method. Any suggestions as far as what I need to consider? Do I need parseInt or else....? Appreciate the advice. Here is what I have so far. If s = "ab3cca4bc", then it should return "abbbccaaaabc", for example of decompress.
class RunLengthCode {
private String pText, cText;
public RunLengthCode () {
pText = "";
cText = "";
}
public void setPText (String newPText) {
pText = newPText;
}
public void setCText (String newCText) {
cText = newCText;
}
public String getPText () {
return pText;
}
public String getCText () {
return cText;
}
public void compress () { // compresses pText to cText
String ans = "";
for (int i = 0; i < pText.length(); i++) {
char current = pText.charAt(i);
int cnt = 1;
String temp = "";
temp = temp + current;
while (i < pText.length() - 1 && (current == pText.charAt(i + 1))) {
cnt++;
i++;
temp = temp + current;
}
if (cnt > 2) {
ans = ans + current;
ans = ans + cnt;
}
else
ans = ans + temp;
setCText(ans);
}
}
public void decompress () {
}
}
public class {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
RunLengthCode myC = new RunLengthCode();
String pText, cText;
System.out.print("Enter a plain text consisting of only lower-case alphabets and spaces:");
pText = in.nextLine();
myC.setPText(pText);
myC.compress();
System.out.println(pText+" => "+myC.getCText());
System.out.print("Enter a compressed text consisting of only lower-case alphabets, spaces and digits:");
cText = in.nextLine();
myC.setCText(cText);
myC.decompress();
System.out.println(cText+" => "+myC.getPText());
}
}

You could create break the string into regx groups and combine them.
The following pattern works
(([A-Za-z]+[\d]*))
This will break your string "ab3cca4bc" into groups of
"ab3", "cca4", "bc"
So in a loop if the last character is a digit, you could multiply the character before it that many times.

Ok, so you've got an input string that looks like ab3cca4bc
1.) Loop over the length of the input String
2.) During each loop iteration, use the String.charAt(int) method to pick up the individual character
3.) The Character class has an isDigit(char) function that you can use to determine if a character is a number or not. You can then safely use Integer.parseInt(String) (you can use myChar+"" to convert a char into a String)
4.) If the char in question is a number, then you'll need to have an inner loop to repeat the previous character the correct number of times. How will you know what the last character was? Maybe have a variable that's instantiated outside the loop that you update each time you add a character on the end?

Related

Replacing Punctuation With Double Exclamation

My purpose is to replace every . and ! with !! when the user enters a text.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a text: ");
String theText = input.nextLine();
System.out.println("The modified text would be: ");
System.out.println(replace(theText));
}
public static String replace(String text)
{
for(int i = 0; i < text.length(); i++)
{
if (text.substring(i,i+1).equals(".") || text.substring(i,i+1).equals("!"))
{
String front = text.substring(0,i);
String back = text.substring(i+1);
text = front + "!!" + back;
}
}
return text;
}
For example, when the user enters "Hello. I am using Java!" , it should return "Hello! I am using Java!!"
The problem is that it returns nothing. What is the error?
P.S. I must use the for loop in the program.
Loop over each character in the String (use charAt, not substring to get one character at a specific index), and add the new characters into a StringBuilder to store the result. It is best not to modify what you are iterating over.
public static String replace(String text) {
StringBuilder sb = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++)
if (text.charAt(i) == '.' || text.charAt(i) == '!') sb.append("!!");
else sb.append(text.charAt(i));
return sb.toString();
}
Alternatively, use String#replaceAll with a regular expression.
return text.replaceAll("[.!]", "!!");

Split a String into number of Characters desired by the user

I want to split a String into n number of characters.
Consider input to be "Example-for-my-Question". Now if I want to split into n=3 characters, output should be "Exa, mpl, e-f, or-, my-, Que, sti, on" and suppose n=4, output should be "Exam, ple-, for-, my-Q, uest, ion" How can you modify the program below without using POSIX.
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String; ");
String inputString = in.nextLine();
System.out.println("How many characters do you want to split into ?");
int n = in.nextInt();
String[] array = inputString.split(" ", n);
System.out.println("Number of words: " + array.length);
for (String arr : array)
System.out.println(arr);
}
}
The simple way to do this is to use String.substring(...) repeatedly to trim N characters off the front of your string ... in a loop.
But if you really want to do this using String.split(...), then I think that the separator regex needs to be a positive look-behind that matches N characters. (It is obscure, and inefficient ... but if regexes are your universal tool ...)
You can use substring for this task.
String sp="StackOverFlow";
int NoOfChars=3;
for(int i=0;i<sp.length();i+=NoOfChars)
{
if(i+NoOfChars<=sp.length())
System.out.println(sp.substring(i,i+NoOfChars));
//Instead add in String ArrayList
else
System.out.println(sp.substring(i));
}
OUTPUT
Sta
ckO
ver
Flo
w
NOTE:Better to use trim() to remove leading or trailing spces
This works for me. In addition to splitting into known lengths, it checks for a null or "too small of a" source string, etc. If a null string is supplied, then a null is returned. If the source string is smaller than the requested split length, then the source string is simply returned.
public static void main (String[] args) throws java.lang.Exception
{
// Three test cases...
String pieces[] = SplitString("Example-for-my-Question", 3);
//String pieces[] = SplitString("Ex", 3);
//String pieces[] = SplitString(null, 3);
if (null != pieces)
{
for (int i = 0; i < pieces.length; i++)
{
System.out.println(pieces[i]);
}
}
}
private static String[] SplitString(String source, int size)
{
String result[] = null;
if (null != source && source.length() > size)
{
int numberOfElements = source.length() / size;
int modulo = source.length() % size;
if (modulo > 0)
{
numberOfElements++;
}
result = new String[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
if (numberOfElements - 1 != i)
{
result[i] = source.substring(i * size, (i * size) + size);
}
else
{
result[numberOfElements - 1] = source.substring(i * size, (i * size) + modulo);
}
}
}
else if (null != source)
{
result = new String[1];
result[0] = source;
}
return result;
}
Please try the following program, but here you have to give input to "N" inside the program itself
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}

java method returning a modified string

I'm trying to create a method that will accept 2 strings as arguments. The first string will be a phrase, the second also a prhase. What I want the method to do is to compare both strings for matching chars. If string 2 has a char that is found in string 1 then replace string 2's instance of the char with an underscore.
Example:
This is the input:
phrase1 = "String 1"
phrase2 = "Strone 2"
The output string is called newPhrase and it will have the string built from the underscores:
newPhrase = "___one 2"
Its not working for me I am doing something wrong.
public class DashedPhrase
{
public static void main(String[] args)
{
dashedHelp("ABCDE","ABDC");
}
public static String dashedHelp(String phrase1, String phrase2)
{
String newPhrase = "_";
for(int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == phrase2.charAt(i))
{
newPhrase.charAt(i) += phrase2.charAt(i);
}
}
System.out.print(newPhrase);
return newPhrase;
}
}
To make it easier for you to understand, you can use StringBuilder and its method setCharAt().
Notice the i < phrase1.length() && i < phrase2.length() in the condition for the for loop. This is to make sure you don't get any ArrayIndexOutOfBounds exception.
public static void main(String[] args)
{
System.out.println("ABCDE");
System.out.println("ABDC");
dashedHelp("ABCDE","ABDC");
System.out.println();
System.out.println();
System.out.println("String 1");
System.out.println("Strone 2");
String phrase1 = "String 1";
String phrase2 = "Strone 2";
dashedHelp(phrase1, phrase2);
}
public static String dashedHelp(String phrase1, String phrase2)
{
StringBuilder newPhrase = new StringBuilder(phrase1);
for(int i = 0; i < phrase1.length() && i < phrase2.length(); i++)
{
if(phrase1.charAt(i) == phrase2.charAt(i))
{
newPhrase.setCharAt(i, '_');
}
}
System.out.print(newPhrase);
return newPhrase.toString();
}
Output:
ABCDE
ABDC
__CDE
String 1
Strone 2
___i_g_1
newPhrase.charAt(i) doesn't let you replace a character, it just returns it. Java's Strings are immutable. I you want to change it you should use StringBuilder. Look into the replace(int start, int end, String str) method.
Since you need to return a string that has the same length as phrase2, you need to iterate over each character of phrase2, and replace the matching characters of both phrases. And, of course, if phrase2 is longer than phrase1, you need to include the remaining characters in the answer. You can try this:
public static String dashedHelp(String phrase1, String phrase2) {
String ans = "";
String subChar = "_";
int i;
for(i = 0; i<phrase2.length(); i++) {
if(i<phrase1.length() && phrase1.charAt(i) == phrase2.charAt(i))
ans += subChar;
else
ans += phrase2.charAt(i);
}
return ans;
}
Hope it helps
Of course, if you need to output phrase1 with underscores in the places where phrase2 has equal characters, you can interchange phrase2 with phrase1 in the above code.
Testing it
The complete class would look like this:
public class MyClass {
public static String dashedHelp(String phrase1, String phrase2) {
// The method code goes here
}
public static void main(String[] args) {
System.out.println(dashedHelp("String 1", "Strone 2"));
}
}
The output of this program is ___o_e_2. This matches (approximately) your desired output.
The code in the example won't even compile.
newPhrase.charAt(i) += phrase2.charAt(i);
That's a bad assignment. It's the same as writing
newPhrase.charAt(i) = newPhrase.charAt(i) + phrase2.charAt(i);
but the expression on the left side of the '=' isn't something to which you can properly assign a value.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

Alternately display any text that is typed in the textbox
// in either Capital or lowercase depending on the original
// letter changed. For example: CoMpUtEr will convert to
// cOmPuTeR and vice versa.
Switch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e )
String characters = (SecondTextField.getText()); //String to read the user input
int length = characters.length(); //change the string characters to length
for(int i = 0; i < length; i++) //to check the characters of string..
{
char character = characters.charAt(i);
if(Character.isUpperCase(character))
{
SecondTextField.setText("" + characters.toLowerCase());
}
else if(Character.isLowerCase(character))
{
SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
}
}}
});
setText is changing the text content to exactly what you give it, not appending it.
Convert the String from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).
Example, start with A. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.
You can use StringUtils.swapCase() from org.apache.commons
This is a better method :-
void main()throws IOException
{
System.out.println("Enter sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String sentence = "";
for(int i=0;i<str.length();i++)
{
if(Character.isUpperCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)+32);
sentence = sentence + ch2;
}
else if(Character.isLowerCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)-32);
sentence = sentence + ch2;
}
else
sentence= sentence + str.charAt(i);
}
System.out.println(sentence);
}
The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.
As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.
You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.
String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();
This is a better approach without using any String function.
public static String ReverseCases(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char temp;
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
temp = (char)(str.charAt(i) - 32);
}
else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
temp = (char)(str.charAt(i) + 32);
}
else {
temp = str.charAt(i);
}
sb.append(temp);
}
return sb.toString();
}
Here you are some other version:
public class Palindrom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word to check: ");
String checkWord = sc.nextLine();
System.out.println(isPalindrome(checkWord));
sc.close();
}
public static boolean isPalindrome(String str) {
StringBuilder secondSB = new StringBuilder();
StringBuilder sb = new StringBuilder();
sb.append(str);
for(int i = 0; i<sb.length();i++){
char c = sb.charAt(i);
if(Character.isUpperCase(c)){
sb.setCharAt(i, Character.toLowerCase(c));
}
}
secondSB.append(sb);
return sb.toString().equals(secondSB.reverse().toString());
}
}
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
Methods description:
*toLowerCase()* Returns a new string with all characters converted to lowercase.
*toUpperCase()* Returns a new string with all characters converted to uppercase.
For example:
"Welcome".toLowerCase() returns a new string, welcome
"Welcome".toUpperCase() returns a new string, WELCOME
If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.
A = 1000001 a = 1100001
B = 1000010 b = 1100010
C = 1000011 c = 1100011
D = 1000100 d = 1100100
...
Z = 1011010 z = 1111010
So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.
Look at the below code for simply changing the string case without using any if-else conditions.
public final class ChangeStringCase {
public static void main(String[] args) {
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
char ans = (char)(str.charAt(i) ^ 32);
System.out.print(ans); // Final Output: hELLO wORLD
}
}
}
Time Complexity: O(N) where N = Length of the string.
Space Complexity: O(1)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String satr=scanner.nextLine();
String newString = "";
for (int i = 0; i < satr.length(); i++) {
if (Character.isUpperCase(satr.charAt(i))) {
newString+=Character.toLowerCase(satr.charAt(i));
}else newString += Character.toUpperCase(satr.charAt(i));
}
System.out.println(newString);
}
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isUpperCase(ch[i])) {
ch[i] = Character.toLowerCase(ch[i]);
} else {
ch[i] = Character.toUpperCase(ch[i]);
}
}
System.out.println(ch);
}
}
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
String str1,str2;
Scanner S=new Scanner(System.in);
str1=S.nextLine();
System.out.println(str1);
str2=S.nextLine();
str1=str1.concat(str2);
System.out.println(str1.toLowerCase());

How do I split strings in J2ME?

How do I split strings in J2ME in an effective way?
There is a StringTokenizer or String.split(String regex) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).
There are a few implementations of a StringTokenizer class for J2ME. This one by Ostermiller will most likely include the functionality you need
See also this page on Mobile Programming Pit Stop for some modifications and the following example:
String firstToken;
StringTokenizer tok;
tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();
There is no built in method to split strings. You have to write it on your own using
String.indexOf() and String.substring(). Not hard.
String.split(...) is available in J2SE, but not J2ME.
You are required to write your own algorithm: related post with sample solution.
I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.
public static String[] split(StringBuffer sb, String splitter){
String[] strs = new String[sb.length()];
int splitterLength = splitter.length();
int initialIndex = 0;
int indexOfSplitter = indexOf(sb, splitter, initialIndex);
int count = 0;
if(-1==indexOfSplitter) return new String[]{sb.toString()};
while(-1!=indexOfSplitter){
char[] chars = new char[indexOfSplitter-initialIndex];
sb.getChars(initialIndex, indexOfSplitter, chars, 0);
initialIndex = indexOfSplitter+splitterLength;
indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);
strs[count] = new String(chars);
count++;
}
// get the remaining chars.
if(initialIndex+splitterLength<=sb.length()){
char[] chars = new char[sb.length()-initialIndex];
sb.getChars(initialIndex, sb.length(), chars, 0);
strs[count] = new String(chars);
count++;
}
String[] result = new String[count];
for(int i = 0; i<count; i++){
result[i] = strs[i];
}
return result;
}
public static int indexOf(StringBuffer sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}
That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:
String myString = "Hello World";
This will print the substring starting from index 6 to the end of the string:
System.out.println(myString.substring(6));
This will print the substring starting from index 0 until index 5:
System.out.println(myString.substring(0,5));
Output of all the code above:
World
Hello
Combine this with the other String functions (indexOf(). etc.) to achieve the desired effect!
Re-reading your question, it looks as though you may have been looking for String.split(). This will split your input string into an array of strings based on a given regex:
String myString = "Hi-There-Gang";
String[] splitStrings = myString.split("-");
This will result in the splitStrings array containing three string, "Hi", "There" and "Gang".
Re-reading your question again, String.split is not available in J2ME, but the same effect can be achieved with substring and indexOf.
public static Vector splitDelimiter(String text, char delimiter) {
Vector splittedString = null;
String text1 = "";
if (text != null) {
splittedString = new Vector();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == delimiter) {
splittedString.addElement(text1);
text1 = "";
} else {
text1 += text.charAt(i);
// if(i==text.length()-1){
// splittedString.addElement(text1);
// }
}
}
splittedString.addElement(text1);
}
return s
}
You can use this method for splitting a delimiter.
In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!!
Use NetBeans.File\Create Project\ Java ME\ MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).
//IDE NetBeans 7.3.1
//author: UserSuperPupsik
//email: usersuperpupsik#gmail.com
package split;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Vector;
public class Midlet extends MIDlet {
public String e1;
public Vector v=new Vector();
public int ma;
int IsD=0;
int vax=0;
public String out[];
private Form f;
public void split0(String text,String delimiter){
if (text!=""){
IsD=0;
int raz=0;
//v.removeAllElements();
v.setSize(0);
int io;
String temp="";
int ni=(text.length()-1);
for(io=0;io<=ni;io++){
char ch=text.charAt(io);
String st=""+ch;
if(io==0 && st.equals(delimiter)){IsD=1;}
if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)
else if(st.equals(delimiter)&&temp!="")//equals (==)
{
IsD=1;
//f.append(temp);
v.addElement(temp);
temp="";
}
if(io==ni && temp!="") {
v.addElement(temp);
temp="";
}
if((io==ni)&&IsD==0&&temp!=""){v.addElement(temp);}
}
if(v.size()!=0){
ma=(v.size());
out=new String[ma];
v.copyInto(out);
}
//else if(v.size()==0){IsD=1; }
}
}
public void method1(){
f.append("\n");
f.append("IsD: " +IsD+"");
if (v.size()!=0){
for( vax=0;vax<=ma-1;vax++){
f.append("\n");
f.append(out[vax]);
}
}
}
public void startApp() {
f=new Form("Hello J2ME!");
Display.getDisplay(this).setCurrent(f);
f.append("");
split0("Hello.World.Good...Luck.end" , ".");
method1();
split0(".",".");
method1();
split0(" First WORD2 Word3 "," ");
method1();
split0("...",".");
method1();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Splited elements located in array called (out).For Example out[1]:Hello.
Good Luck!!!
Another alternative solution:
public static Vector split(String stringToSplit, String separator){
if(stringToSplit.length<1){
return null;
}
Vector stringsFound = new Vector();
String remainingString = stringToSplit;
while(remainingString.length()>0){
int separatorStartingIndex = remainingString.indexOf(separator);
if(separatorStartingIndex==-1){
// Not separators found in the remaining String. Get substring and finish
stringsFound.addElement(remainingString);
break;
}
else{
// The separator is at the beginning of the String,
// Push the beginning at the end of separator and continue
if(remainingString.startsWith(separator)){
remainingString = remainingString.substring(separator.length());
}
// The separator is present and is not the beginning, add substring and continue
else{
stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));
remainingString = remainingString.substring(separatorStartingIndex + separator.length());
}
}
}
return stringsFound;
}

Categories