String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
StringBuilder code=new StringBuilder(cdd);
String temp;
for(int i=0;i<code.length();i++){
temp=code.substring(sindex, eindex++);
if(Arrays.asList(cod).contains(temp)){
int j=Arrays.asList(cod).indexOf(temp);
int z=code.indexOf(temp);
StringBuilder y = code.delete(z, z+temp.length());
temp=y.toString();
real+=enc[j];
System.out.println(y);
}
}
I have these two arrays enc[] and cod[], contains characters and codes respectively what i want to do is just check each value of cod array in cdd string and replace it with its respective String from enc[]...
By running this code i am getting only "w" while the result was suppose to be "welcome".
Try this code - i have refactored yours :)
public class enc {
private static boolean valueFound=false;
public static void main(String[] args) {
String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
do {
for (int i = 0; i < cod.length; i++) {
if (cdd.startsWith(cod[i])) {
real += enc[i];
cdd = cdd.substring(cod[i].length());
valueFound = true;
} else {
valueFound = false;
}
}
}
while(valueFound);
System.out.println(real);
}
}
Related
I want to search how many times a string appear in another string
It does not work correctly when i put an similar string at the end.
public class C3_Project3_WPr {
public static void main(String[] args) {
String strn1="AliAliAli";
String strn2="AliAliSinaAli";
String strn3="Ali";
int count1=StringCounter(strn1, strn3);
System.out.println(count1);
int count2=StringCounter(strn2, strn3);
System.out.println(count2);
}
//ُString in String Method
static int StringCounter(String str1, String str2){
int counter=0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for(int i= 0; i<str1.length(); i++){
if(str1.contains(str2)){
counter++;
str1= str1.substring(str2.length());
}
}
return counter;
}
}
Solution to your problem is here
public static void main(String[] args) {
String strn1 = "AliAliAliwewdwdweAli";
String strn2 = "AliAliSinaAliAlAli";
String strn3 = "Ali";
int count1 = StringCounter(strn1, strn3);
System.out.println(count1);
int count2 = StringCounter(strn2, strn3);
System.out.println(count2);
}
// ُString in String Method
static int StringCounter(String str1, String str2) {
int counter = 0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for (int i = str1.indexOf(str2); i >= 0; i = str1.indexOf(str2, i + str2.length())) {
counter++;
}
return counter;
}
}
When modifying str1 you only take in to account the length of the search string, but ignore the index in which it was found. Fixing this (e.g., by using indexOf), will fix your results too:
int index = str1.indexOf(str2);
while (index >= 0) {
counter++;
index = str1.indexOf(str2, index + str2.length());
}
Use recursive method: It's quick and easy way to solve your problem:
static int StringCounter(String str1, String str2){
return (str1.contains(str2)) ? 1 + StringCounter(str1.replaceFirst(str2, ""), str2) : 0;
}
How can I get the String and the int values from a String like this : "a:10,b:15,c:20,d:30"
String mixedString = "a:10,b:15,c:20,d:30";
String requiredArray1[] = [a,b,c,d];
int requiredArray2[] = [10,15,20,20];
You can loop your String and test your String one by one:
First
You need to split your String to :
String myString = "a:10,b:15,c:20,d:30";
//split the String to get only the Strings and int in your case you need to split with , and :
String mixedString[] = myString.split(":|\\,");
Second
Test If the String is Integer then return true and insert it to the array of Integers, else Insert it to the array of Strings:
public static boolean test(String s){
try{
Integer i = Integer.parseInt(s);
return true;
}catch(Exception e){
return false;
}
}
Here how your program should look like:
public static void main(String[] args) {
String myString = "a:10,b:15,c:20,d:30";
String mixedString[] = myString.split(":|\\,");
String requiredArray1[] = new String[mixedString.length];
int requiredArray2[] = new int[mixedString.length];
int s = 0;
int n = 0;
for (int i = 0; i < mixedString.length; i++) {
if (!test(mixedString[i])) {
requiredArray1[s] = mixedString[i];
s++;
} else {
requiredArray2[n] = Integer.parseInt(mixedString[i]);
n++;
}
}
}
public static boolean test(String s) {
try {
Integer i = Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
}
If your mixed String is as you show in your post where every alpha character is always followed by a colon delimiter (:) and then a string representation of a numerical value, you really don't need an additional method to test for whether or not a numerical value is there. You simply know its there just as you know there is a alpha value there as well...or...maybe you don't and maybe you should test for the alpha as well. You don't specify either way within your post what different possibilities might exist within the mixed string. Therefore, we can assume that:
Every alpha section is delimited with a colon (:) and then followed by a string representation of a numerical value which so far does indeed appear to be Integer. This is then followed by a comma (,) delimiter and yet another colon delimited alpha/numerical pair.
String mixedString = "a:10,b:15,c:20,d:30";
System.out.println("Original String: \"" + mixedString + "\"\n");
String[] mStringArray= mixedString.split(",");
String[] alphaArray = new String[mStringArray.length];
int[] numericArray = new int[mStringArray.length];
for (int i = 0; i < mStringArray.length; i++) {
String[] tmp = mStringArray[i].split(":");
alphaArray[i] = tmp[0];
numericArray[i] = Integer.parseInt(tmp[1]);
}
// Display contents of the two Arrays
System.out.println("Elements From Alpha Array");
for (int i = 0; i < alphaArray.length; i++) {
System.out.println(alphaArray[i]);
}
System.out.println("\nElements From Numeric Array");
for (int i = 0; i < numericArray.length; i++) {
System.out.println(numericArray[i]);
}
public static void main(String[] args) {
String myString = "a:10,b:15,c:20,d:30";
// extract all numbers (All elements are numbers so you can convert it to int easily )
String[] requiredArray1 = extractAllAccordingToRegex("\\d+", myString);
// extract all characters
String[] requiredArray2 = extractAllAccordingToRegex("[a-zA-Z]+",myString);
}
static String[] extractAllAccordingToRegex(String inputRegex, String input) {
List<String> extractedItems = new ArrayList<String>();
Pattern reg = Pattern.compile(inputRegex);
Matcher m = reg.matcher(input);
while (m.find()) {
extractedItems.add(m.group());
}
return extractedItems.toArray(new String[1]);
}
I'm trying to create a method that replace all instances of a certain character in a word with a new character. This is what I have so far:
public class practice {
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3); }
public static String updatePartialword(String partial, String secret, char c) {
String newPartial = "";
int len = secret.length();
for (int i=0; i<=secret.length()-1; i++){
char x = secret.charAt(i);
if (c==x) {
String first = partial.substring(0,i);
String second = partial.substring(i+1,len);
newPartial = first+x+second;
}
}
return newPartial;
}
}
I want it to return t--t, but it will only print the last t. Any help would be greatly appreciated!
Java already has a built in method in String for this. You can use the the replace() method to replace all occurrences of the given character in the String with the another character
String str = "Hello";
str.replace('l', '-'); //Returns He--o
str.replace('H', '-'); //Returns -ello
I suspect you are looking for something like
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3);
}
public static String updatePartialword(String partial, String secret, char c) {
char[] tmp = partial.toCharArray();
for (int i = 0; i < secret.length(); i++) {
char x = secret.charAt(i);
if (c == x) {
tmp[i] = c;
}
}
return new String(tmp);
}
In your code you overwrite the String each time you found the character. Instead of overwriting, you should expand the string each time.
public class practice {
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3);
}
public static String updatePartialword(String partial, String secret, char c) {
StringBuilder sb = new Stringbuilder();
sb.append(""); // to prevent the Stringbuilder from calculating with the chars
for (int i = 0; i < partial.lenght; i++)
if (secret.charAt(i) == c)
sb.append(c);
else
sb.append('-');
return sb.toString();
}
}
I'm a beginner at java, i have been playing around with arrays, but I can't understand whats going wrong.
This is the class:
public class StringArrayUtil {
public static void print(String [] sArray){
for(int i = 0; i<sArray.length; i++){
if(sArray[i] !=null){
System.out.println("Indice: "+i+ " String: "+sArray[i] + "\t");
}
}
}
public static int indexOf(String [] sArray, String sSearch, int s){
for(int i = s; i < sArray.length; i++){
if(sArray[i] != null && sSearch != null && sSearch.equals(sArray[i])){
return i;
}
}
return -1;
}
public static int indexOf(String [] sArray, String sSearch){
return indexOf(sArray, sSearch, 0);
}
public static int indexOfEmpty(String[] sArray){
return indexOf (sArray,null,0);
}
public static int put(String[] sArray, String newS){
for(int i = 0; i<sArray.length; i++){
if(sArray[i] == null){
sArray[i]=newS;
return i;
}
}
return -1;
}
public static int remove(String sArray, String removeS){
int times = 0;
for(int i = 0; i < sArray.length; i++){
if(removeS.equals(sArray[i]) ){
sArray[i] = null;
times ++;
}
return times;
}
}
public static String fillArray (String messege, int n){
String[] result = new String[n];
for(int i = 0; i<result.length; i++){
result[i] = Scanner.getString (messege);
}
return result;
}
}
And this is my main:
class StringArrayUtilTester {
public static void main(String [] args){
System.out.println("----------Welcome to StringMaster 2.0----------");
int z=5;
String a= "-Create a String: ";
String [] array = StringArrayUtil.fillArray(a,z);
String search = Scanner.getString("-String SearchBox! find and delete String: ");
int i = StringArrayUtil.indexOf(array, search);
if (i != -1){
System.out.println("-The String belongs to the Array!");
array[i] = null;
System.out.println("...loading....");
System.out.println("-The string has been deleted.");
}
else{
System.out.println("-String not found, try another one!");
}
String replace = Scanner.getString("-Replace with new string: ");
int e = StringArrayUtil.indexOfEmpty(array);
if(e != -1){
array[e] = replace;
}
System.out.println("-Final Array of Strings: ");
StringArrayUtil.print(array);
}
}
The errors I get when I try to javac i cant understand. Am I not doing my fillArray correctly? :
StringArrayUtilTester.java:7: error: incompatible types: String cannot be converted to String[]
array = StringArrayUtil.fillArray(a,z);
The return type on your fillArray method is String which isn't String[]
You need to make the method return a String[] by changing the return type: public String[] fillArray(...)
fillArray returns a String.
You should change the prototype to public static String[] fillArray (String messege, int n){
The return type of fillArray should be String[]
public static String[] fillArray (String messege, int n){
String[] result = new String[n];
for(int i = 0; i<result.length; i++){
result[i] = Scanner.getString (messege);
}
return result;
}
Two problems in the method fillArray
The method is expecting a String but you return a String[]. Probably the method signature should be String[]
Scanner doesn't have a static method getString
You need to create an instance of Scanner prior to using it:
Scanner scan = new Scanner(System.in);
Then you can do
result[i] = scan.next();
I am trying to create a program that translates English to PigLatin. I have most of the components, but if I enter in more than one word, it only translates the first word. Where is the issue and how do I fix it.
public class PigLatin{
public static String translate(String phrase){
String [] returnArray=phrase.split(" ");
String [] translateArray=new String [returnArray.length];
for(int i=0;i<returnArray.length;i++){
translateArray[i]=translateWord(returnArray[i]);
}
return StringLib.join(translateArray, " ");//translated Array
}
public static String translateWord(String word) {
String tword=word;
int indexVowel=indexOfFirstVowel(tword);
if(indexOfFirstVowel(tword)==0){
tword=tword+"yay";
}
else {
tword=tword.substring(indexOfFirstVowel(tword),tword.length())+tword.substring(0,indexOfFirstVowel(tword))+"ay";
}
return tword;
}
public static int indexOfFirstVowel(String word) {//check where the first vowel is
String vowels = "aeiouy";
String loweredWord=word.toLowerCase();
for (int index=0;index<loweredWord.length();index++){
if(vowels.contains(String.valueOf(loweredWord.charAt(index)))){
return index;
}
}
return -1;
}
public static void main(String [] args){
Scanner inp=new Scanner(System.in);
System.out.println("Please enter a phrase:");
String trans=translate(inp.next());
System.out.println("Here is your phrase in Pig Latin.");
System.out.println(trans);
}
String.join translates the array into a String and here is that code
public class StringLib {
public static String join(String[] strs, String sep) {
String joined = "";
if (strs.length > 0) {
joined = strs[0];
for (int i = 1; i < strs.length; i++) {
joined = joined + sep + strs[i];
}
}
return joined;
}
Change this line in your main method
String trans = translate(inp.next());
Into
String trans = translate(inp.nextLine());