Here's my code.
public static String hBlanks(String a, String b){
StringBuilder blanks = new StringBuilder();
int j;
for(int x = 0; x < a.length(); x++){
blanks.append('-');
}
System.out.println(blanks);
String strBlanks = blanks.toString();
for(int i = 0; i < a.length(); i++){
j = 0;
while(j < b.length()){
boolean check = a.contains(b.charAt(j));
//I keep getting an error on the boolean check = a.contains(b.charAt(j)); line. It says: "contains(java.lang.CharSequence) in java.lang.String cannot be applied to (char)"
if(check == true){
strBlanks = blanks.replace('-', "" + a.charAt(i));
//And I get another error at the str = strBlanks.replace('-', "" + a.charAt(i)); line. That one says "cannot find symbol
symbol : method replace(char,java.lang.String)
location: class java.lang.String"
}else{
j++;
}
}
return strBlanks;
}
}
To get rid of your compilation issues,
Change strBlanks.replace('-', "" + a.charAt(i)); to
strBlanks.replace('-', a.charAt(1));
Also change a.contains(b.charAt(j)); to
a.contains("" + b.charAt(1));
How about just one line, instead of all that code:
public static String wordBlanks(String a, CharSequence b){
return a.replaceAll("[^" + b + "]", "-");
}
This works by creating a regex that matches every character not in b and using that to replace ever occurrence in a with a dash.
Related
I'm trying to print my array separated by pipes ("|"), but it keeps printing before the println statement in my main method. It should look like this:
90|0|-12|25|10412|445|-32|1
I've been messing with the return statement, but I can't think of anything else to do.
static String arrayToString(int[] input){
String toString = "";
for (int i = 0; i < input.length; i++){
if (i > 0){
System.out.print("|");
} else if (i == input.length - 1){
System.out.print("");
}
System.out.print(input[i]);
}
return toString;
}
public static void main(String[] args) {
int[] testArray1 = {90, 0, -12, 25, 10412, 445, -32, 1};
CommonArrayAlgorithms testingObject = new CommonArrayAlgorithms();
System.out.println("Testing arrayToString");
String arrayString;
arrayString = testingObject.arrayToString(testArray1); //<--- prints here
System.out.println(" arrayToString returned: " + arrayString); //<--- should print here
My output is:
Testing arrayToString
90|0|-12|25|10412|445|-32|1 arrayToString returned:
When it should be:
Testing arrayToString
arrayToString returned: 90|0|-12|25|10412|445|-32|1
In your method you are outputting to the console with System.out.print where you should be adding to your toString variable.
Change you method as follows (keeping your current logic):
static String arrayToString(int[] input){
String toString = "";
for (int i = 0; i < input.length; i++){
if (i > 0){
toString += "|";
} else if (i == input.length - 1){
toString += "";
}
toString += input[i];
}
return toString;
}
It is because you are calling the method that prints the array before your title string, and also your method returns an empty string that you tried to store on another string and print it after your title.
So the solution for this :
System.out.print("your title: "+testingObject.arrayToString(array1));
The question is to count how many permutations of a string B have an equivalent pattern into a bigger string A. For example, if A="aabbccd" and B="xx", then it should print 3, since "aa", "bb", "cc" are all substrings of A which share the same pattern as B.
I have tried to pass the substrings as numbers, such as xx becomes "11" and do the same for string A, but I still can't get it to work. Any ideas? Length can be up to 10^7.
Here's the code for changing pattern:
void transform(int* dest, char* original, int len) {
int j=1;
Al[original[0]-'a']=j;
dest[0]=j;
j++;
for (int i=1;i<len;i++) {
if (Al[original[i]-'a']==0)
Al[original[i]-'a']=j++;
dest[i]=Al[original[i]-'a'];
}
}
Concept: Use Regular Expressions
You would need the following regular expression (\\w)\\1{(REPETITIONS-1)}
I don't know about C but Java provides a library to compile RegEx patterns. Here's a class that implements just what you want:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPatternPermutation {
public static void main(String[] args) {
int REPETITIONS = 3;
String REGEX = "(\\w)\\1{" + (REPETITIONS-1) + "}";
String INPUT = "abbbbbbccddeffff";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count = 0;
while(m.find()){
String match = m.group();
System.out.println(match);
count++;
}
System.out.println(count);
}
}
Here's a test of the code above: https://ideone.com/5nztaa
Here's a useful website to test any RegEx: https://regexr.com/
Without Regular Expressions
public class StringPatternPermutation {
public static void main(String[] args) {
String a = "abjjjiixsssppw";
String b = "qwwwee";
String patternA = detectPattern(a);
String patternB = detectPattern(b);
System.out.println("-String A: " + a);
System.out.println("-Pattern A: " + patternA);
System.out.println("-String B: " + b);
System.out.println("-Pattern B: " + patternB);
System.out.println("-A contains B? " + patternA.contains(patternB));
int count = 0;
int index = 0;
while((index = patternA.indexOf(patternB)) != -1){
count++;
patternA = patternA.substring(index+1, patternA.length());
}
System.out.println("-Number of occurances: " + count);
}
private static String detectPattern(String a){
StringBuilder sb = new StringBuilder();
char prev = a.charAt(0);
int count = 1;
for(int i = 1; i < a.length(); i++){
char curr = a.charAt(i);
if(curr == prev)
count++;
else {
sb.append(count + ", ");
prev = curr;
count = 1;
}
if(i == a.length() - 1){
sb.append(count);
}
}
return sb.toString();
}
}
Test it on ideOne: https://ideone.com/w422Du
If the given input is a1bc2def3 then output should be abcbcdefdefdef
Whenever the number comes then we should repeat previous substring that many number of times.
Please provide the algorithm or code to accomplish this.
Here's another approach that doesn't rely on regex.
public String splitRepeat(String str)
{
StringBuilder out = new StringBuilder();
boolean number = false;
for(int i=0,j=0,k=0; i<=str.length(); i++)
{
if(i==str.length() || Character.isDigit(str.charAt(i)) != number)
{
if(number)
{
for(int r = Integer.parseInt(str.substring(j, i)); r>0; r--)
{
out.append(str.substring(k, j));
}
}
else
{
k=j;
}
j=i;
number = !number;
}
}
return out.toString();
}
My suggestion would be:
Try using regex so you can get an array of numbers and characters,
then convert the number Parsable elements of the array into an integer,
after that loop with the index of the arrays to append n-times the characters of the array
then print the final result
Example:
public static void main(String[] args) {
String stringToProcess = "a1bc2def3";
String[] regexSplitted = stringToProcess.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
String appender = "";
for (int i = 0; i < regexSplitted.length; i++) {
try {
int kilo = Integer.parseInt(regexSplitted[i]);
for (int j = 0; j < kilo; j++) {
sb.append(appender).append(regexSplitted[i - 1]);
appender = "-";
}
} catch (NumberFormatException e) {
}
}
System.out.println(sb.toString());
}
this will print
a-bc-bc-def-def-def
that is pretty much what you are looking for.
Currently the code should replace all spaces in a string with %20. For the most part, I think the logic is right on the method I make a call to, but when I want to see the returned result I my main method prints nothing -- it prints a blank for the string. Could someone direct me where my my logic in turning the array into a string is incorrect? Thanks for the time and help. I attached my code for the method in case you guys needed it. Sorry if the mistake is dumb.
public class replaceSpaces {
public static void main(String[] args) {
char[] data = checkfor20("yo o");
String text = String.valueOf(data); //turn char array into string representation
System.out.println(" new one: " + text);
}
private static char[] checkfor20(String string) {
int check = string.length(); //length of string
int spaceCount = 0, newLength; //count spaces and new length with %20 put in
char[] charstring = string.toCharArray(); // turn string into char array
for(int i = 0; i < check ; i++) { //get space count for newlenght
if (charstring[i] == ' ') {
spaceCount++;
}
}
newLength = check + (spaceCount * 2);
char[] newArray = new char[newLength];
for(int i = check - 1; i >= 0; i--) {
if(newArray[i] == ' ') { //get spaces and put it
newArray[newLength - 1 ] = '0';
newArray[newLength - 2 ] = '2';
newArray[newLength - 3 ] = '%';
newLength = newLength - 3;
}
else {
newArray[newLength - 1] = charstring[i];
newLength = newLength - 1;
}
}
return newArray; //return the new char array
}}
Why not newstring = oldstring.replace(" ","%20");?
Apologizes for the mistake on my part I was supposed to just change my array into
if(charstring[i] == ' ')
rather than the new array I created.
I have been playing around with programming for arduino but today i've come across a problem that i can't solve with my very limited C knowledge.
Here's how it goes.
I'm creating a pc application that sends serial input to the arduino (deviceID, command, commandparameters). This arduino will transmit that command over RF to other arduino's. depending on the deviceID the correct arduino will perform the command.
To be able to determine the deviceID i want to split that string on the ",".
this is my problem, i know how to do this easily in java (even by not using the standard split function), however in C it's a totally different story.
Can any of you guys tell me how to get this working?
thanks
/*
Serial Event example
When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and
clears it.
A good test for this is to try it with a GPS receiver
that sends out NMEA 0183 sentences.
Created 9 May 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent
*/
String inputString; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
String[] receivedData;
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
if (inChar == '\n') {
stringComplete = true;
}
// add it to the inputString:
if(stringComplete == false) {
inputString += inChar;
}
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
}
}
String[] splitCommand(String text, char splitChar) {
int splitCount = countSplitCharacters(text, splitChar);
String returnValue[splitCount];
int index = -1;
int index2;
for(int i = 0; i < splitCount - 1; i++) {
index = text.indexOf(splitChar, index + 1);
index2 = text.indexOf(splitChar, index + 1);
if(index2 < 0) index2 = text.length() - 1;
returnValue[i] = text.substring(index, index2);
}
return returnValue;
}
int countSplitCharacters(String text, char splitChar) {
int returnValue = 0;
int index = -1;
while (index > -1) {
index = text.indexOf(splitChar, index + 1);
if(index > -1) returnValue+=1;
}
return returnValue;
}
I have decided I'm going to use the strtok function.
I'm running into another problem now. The error happened is
SerialEvent.cpp: In function 'void splitCommand(String, char)':
SerialEvent:68: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
SerialEvent:68: error: 'null' was not declared in this scope
Code is like,
String inputString; // a string to hold incoming data
void splitCommand(String text, char splitChar) {
String temp;
int index = -1;
int index2;
for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) {
Serial.println(temp);
}
for(int i = 0; i < 3; i++) {
Serial.println(command[i]);
}
}
This is an old question, but i have created some piece of code that may help:
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
This function returns a single string separated by a predefined character at a given index. For example:
String split = "hi this is a split test";
String word3 = getValue(split, ' ', 2);
Serial.println(word3);
Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.
Hope this help!
Implementation:
int sa[4], r=0, t=0;
String oneLine = "123;456;789;999;";
for (int i=0; i < oneLine.length(); i++)
{
if(oneLine.charAt(i) == ';')
{
sa[t] = oneLine.substring(r, i).toInt();
r=(i+1);
t++;
}
}
Result:
// sa[0] = 123
// sa[1] = 456
// sa[2] = 789
// sa[3] = 999
For dynamic allocation of memory, you will need to use malloc, ie:
String returnvalue[splitcount];
for(int i=0; i< splitcount; i++)
{
String returnvalue[i] = malloc(maxsizeofstring * sizeof(char));
}
You will also need the maximum string length.
The C way to split a string based on a delimiter is to use strtok (or strtok_r).
See also this question.
I think your idea is a good start point. Here is a code that i use (to parse HTTP GET REST requests with an Ethernet shield).
The idea is to use a while loop and lastIndexOf of and store the strings into an array (but your could do something else).
"request" is the string you want to parse (for me it was called request because.. it was).
int goOn = 1;
int count = -1;
int pos1;
int pos2 = request.length();
while( goOn == 1 ) {
pos1 = request.lastIndexOf("/", pos2);
pos2 = request.lastIndexOf("/", pos1 - 1);
if( pos2 <= 0 ) goOn = 0;
String tmp = request.substring(pos2 + 1, pos1);
count++;
params[count] = tmp;
// Serial.println( params[count] );
if( goOn != 1) break;
}
// At the end you can know how many items the array will have: count + 1 !
I have used this code successfully, but i thing their is an encoding problem when i try to print params[x]... i'm alos a beginner so i don't master chars vs string...
Hope it helps.
I believe this is the most straight forward and quickest way:
String strings[10]; // Max amount of strings anticipated
void setup() {
Serial.begin(9600);
int count = split("L,-1,0,1023,0", ',');
for (int j = 0; j < count; ++j)
{
if (strings[j].length() > 0)
Serial.println(strings[j]);
}
}
void loop() {
delay(1000);
}
// string: string to parse
// c: delimiter
// returns number of items parsed
int split(String string, char c)
{
String data = "";
int bufferIndex = 0;
for (int i = 0; i < string.length(); ++i)
{
char c = string[i];
if (c != ',')
{
data += c;
}
else
{
data += '\0';
strings[bufferIndex++] = data;
data = "";
}
}
return bufferIndex;
}