How to convert int value into string means my string will be 42646 character its mod 42600 how to show and print this character and how?
int count = image_length.length(); //count=42646
System.out.println(count);
int mod = count % length; //46
int rem = count - mod; //42600
String rem_value = String.valueOf(rem);
// I want to get string through reminder value 42600 & how
String[] split = rem_value.split("[^a-zA-Z/]", length);
getSaltString();
photoName = randStr + "_IMG.jpg";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < split.length; i++) {
url_part = String.valueOf(stringBuilder.append(split[i]));
new RegisterImageThread(ActivityRegisterUploadPhoto.this).execute(photoName, url_part + i);
}
new RegisterImageThread(ActivityRegisterUploadPhoto.this).execute(photoName, url_part+rem_value);
So you want to split the numeric String "42600" to an array right?
Replace the line:
String[] split = rem_value.split("[^a-zA-Z/]", length);
to something like this:
String rem_value = "42600"; //your rem_value
int[] split = new int[rem_value.length()];
for (int i = 0; i < rem_value.length(); i++) {
split[i] = Character.getNumericValue(rem_value.charAt(i));
}
//print the result
Arrays.stream(split).forEach(s -> System.out.println(s));
Related
So I'm trying to write an algorithm that counts the number of occurrences of some pattern, say "aa", within a string, say "aaabca." The number of patterns in that string should return an integer, in this case 2, because the first three characters contain two occurrences of the pattern.
What I have finds the number of patterns under the assumption the existing occurrences of a pattern is NOT overlapping:
public class Pattern{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string: ");
String s = scan.nextLine();
String[] splittedInput = s.split(";");
String pattern = splittedInput[0];
String blobs = splittedInput[1];
Pattern p = new Pattern();
p.count(pattern, blobs);
}
public static void count(String pattern, String blobs){
String[] substrings = blobs.split("[|]");
int numOccurences = 0;
int[] instances = new int[substrings.length];
int patternLength = pattern.length();
for (int i = 0; i < instances.length; i++){
int length = substrings[i].length();
String temp = substrings[i];
temp = temp.replaceAll(pattern, "");
int postLength = temp.length();
numOccurences = (length - postLength) / pattern.length();
instances[i] = numOccurences;
numOccurences = 0;
}
int sum = 0;
for (int i = 0; i < instances.length; i++){
System.out.print(instances[i] + "|");
sum += instances[i];
}
System.out.print(sum);
}
}
Any suggestions?
I would personally compare the pattern as a substring in this case. For example a run of a single String from your array would look like this:
//Initial values
String blobs = "aaaabcaaa";
String pattern = "aab";
String[] substrings = blobs.split("[|]");
//The code I added that should placed into the loop
int numOccurences = 0;
String str = substrings[0];
for (int k = 0; k <= (str.length() - pattern.length()); k++)
{
if (str.substring(k, k + pattern.length()).equals(pattern))
{
numOccurences++;
}
}
System.out.println(numOccurences);
If you want to run this on each String in your array simply modify String str = substrings[0] to String str = substrings[i] and iterate over the array storing the final numOccurences as you please.
Example Run:
String is aaaabcaaa
Pattern is aa
Output is 5 occurences
For one String, match is the String you're looking for:
int len = theStr.length ();
int start = 0;
int pos;
int count = 0;
while ((start < len) && ((pos = theStr.indexOf (match, start)) >= 0))
{
++count;
start = pos + 1;
}
If you use Java 8 you can count this value in the following way.
Example:
String blobs = "aaabcaaa";
String pattern = "aa";
List<String> strings = Arrays.asList(blobs.split(""));
long count = IntStream.range(0, strings.size())
.mapToObj(index -> index < strings.size() - 1 ? strings.get(index) + strings.get(index + 1) : strings.get(index - 1))
.filter(str -> str.equals(pattern))
.count();
System.out.println("Result count: " + count);
Continually taking substrings and using the startsWith method seems to work pretty well.
String pat = "ss";
String str = "kskslsksaaaslsslssskssssllsssss";
int count = 0;
while (str.length() >= pat.length()) {
count += str.startsWith(pat) ? 1 : 0;
str = str.substring(1);
}
System.out.println("count = " + count);
You can also take a similar approach with streams.
long count = IntStream.range(0, str.length()).mapToObj(
n -> str.substring(n)).filter(n -> n.startsWith(pat)).count();
System.out.println("count = " + count);
But in this case I actually prefer the non-stream approach.
I was working on a Java coding problem and encountered the following issue.
Input: A String -> "Code"
Output Expected: A string -> CCoCodCode
My Code snippet: (Note: In comments I have written what I expect upon passing the string)
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
String[] result = new String[size];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
Output I am getting:
CCoCodCodenullnullnullnullnullnullnullnullnullnullnullnull
Why is null getting stored although I have reduced the size and how can I remove it?
NOTE: I need to solve this using arrays. I know it is much easier using List.
If you want to keep the current structure of your code, get rid of the first for loop.
And create String[] array = new String[n]
public static String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n]; //you want your String array to contain 4 strings
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
public class Answer {
public static String answer(String input){
StringBuilder sb = new StringBuilder(((input.length() + 1) * input.length()) / 2);
for (int i = 1; i <= input.length(); i++) {
sb.append(input.substring(0, i));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(answer("Code"));
}
}
Below statements are not required:
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
You just need to change the array size from
String[] result = new String[size];
to
String[] result = new String[n];
for your program to give the expected output.
If I understand ur problem correctly to print the pattern then u can use below code,
public String printPattern(String input){
//Holds the iteration value by index
int previous=0;
//It holds the result characters
String result=null;
StringBuilder strBuilder=new StringBuilder();
//first loop to iterate only till input string length
for(int i=0;i<input.length();i++){
//checking iteration lenght with input string length
if(previous<input.length()){
//incrementing iteration for reading characters from input string
previous++;
//main loop for previous iteration value check and iterate
for(int j=0;j<previous;j++){
//converting string to Character array
char a []=input.toCharArray();
//using string builder to build the string from characters
strBuilder.append((a[j]));
//setting the value to stringbuilder by converting it in string
result=strBuilder.toString();
}
}
}
return result;
}
Size should be the length of string. Code's length is 4. Code will produce {C, Co, Cod, Code}.
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
System.out.println(Arrays.toString(result));
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
String input = "Code";
String output[] = IntStream.range(0, input.length()+1)
.mapToObj(i -> input.substring(0, i))
.toArray(String[]::new);
Using Java, how would I convert "Paul, John, Ringo" to
Paul
John
Ringo
But while using a loop that searches for the commas and pulls out the words between them? I can't use anything like string split, strictly a loop and pretty simple java. Thanks!
String str = "Paul, John, Ringo";
List<String> words = new ArrayList<String>();
int cIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
String temp = str.substring(cIndex, i).trim();
cIndex = i + 1;
words.add(temp);
}
}
String temp = str.substring(str.lastIndexOf(',')+1,str.length()).trim();
words.add(temp);
List<String> list = new List<String>();
String text = "your, text, here";
int indexTraversed = 0;
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
}
String[] array = list.toArray();
and if you can't use List :
String[] list = new String[100];
int counter = 0;
String text = "your, text, here";
int indexTraversed = 0; // declaring and assigning var
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
counter ++;
}
Then read the list array until counter.
I am making a method which will return a String[] containing valid combinations of words that differ by one letter. The method takes as String array containing a dictionary of words as the first parameter, and two other strings containing the words one and two respectively as the second and third parameters.
Here is my method:
public static String[] findCombos(String[] dict, String a, String b){
char[] wordA = a.toCharArray();
char[] wordB = b.toCharArray();
int length = wordA.length;
List<String> validCombos = new ArrayList<String>();
Arrays.sort(dict);
//wordA
for(int i = 0; i<length; i++){
char tmp = wordA[i];
wordA[i] = 0;
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString().trim();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
int lengthb = wordB.length;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString();
for(int j = 0; j<lengthb; j++){
tmpWordB = new StringBuffer(tmpWordB).insert(j ,tmp).toString();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordA[i] = tmp;
}
}
}else{
wordA[i] = tmp;
}
}
//wordB
int lengthb = b.length();
for(int i = 0; i<lengthb; i++){
char tmp = wordB[i];
wordB[i] = 0;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString().trim();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
int lengtha = a.length();
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString();
for(int j = 0; j< lengtha; j++){
tmpWordA = new StringBuffer(tmpWordA).insert(j, tmp).toString();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordB[i] = tmp;
}
}
}else{
wordB[i] = tmp;
}
}
String[] res = validCombos.toArray(new String[0]);
return res;
}
The array has been sorted and I am certain that the element in question is in the array, however the search keeps returning a negative number and automatically branching to the else clause. Any ideas? Here is a link to the dictionary:
Dictionary - PasteBin
You are not removing the character at index i, you are replacing the character at index i with 0, that false assumption breaks your algorithm.
Delete a character by index from a character array with StringBuilder
String mystring = "inflation != stealing";
char[] my_char_array = mystring.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(mystring);
sb.deleteCharAt(10);
my_char_array = sb.toString().toCharArray();
System.out.println(my_char_array); //prints "inflation = stealing"
The above code removes the exclamation mark from the character array.
Roll your own java function to remove a character from a character array:
String msg = "johnny can't program, he can only be told what to type";
char[] mychararray = msg.toCharArray();
mychararray = remove_one_character_from_a_character_array_in_java(mychararray, 21);
System.out.println(mychararray);
public char[] remove_one_character_from_a_character_array_in_java(
char[] original,
int location_to_remove)
{
char[] result = new char[original.length-1];
int last_insert = 0;
for (int i = 0; i < original.length; i++){
if (i == location_to_remove)
i++;
result[last_insert++] = original[i];
}
return result;
}
//The above method prints the message with the index removed.
Source:
https://stackoverflow.com/a/11425139/445131
I have a problem wherein I have two strings, the length of one of which I will know only upon execution of my function. I want to write my function such that it would take these two stings and based upon which one is longer, compute a final string as under -
finalString = longerStringChars1AND2
+ shorterStringChar1
+ longerStringChars3and4
+ shorterStringChar2
+ longerStringChars5AND6
...and so on till the time the SHORTER STRING ENDS.
Once the shorter string ends, I want to append the remaining characters of the longer string to the final string, and exit. I have written some code, but there is too much looping for my liking. Any suggestions?
Here is the code I wrote - very basic -
public static byte [] generateStringToConvert(String a, String b){
(String b's length is always known to be 14.)
StringBuffer stringToConvert = new StringBuffer();
int longer = (a.length()>14) ? a.length() : 14;
int shorter = (longer > 14) ? 14 : a.length();
int iteratorForLonger = 0;
int iteratorForShorter = 0;
while(iteratorForLonger < longer) {
int count = 2;
while(count>0){
stringToConvert.append(b.charAt(iteratorForLonger));
iteratorForLonger++;
count--;
}
if(iteratorForShorter < shorter && iteratorForLonger >= longer){
iteratorForLonger = 0;
}
if(iteratorForShorter<shorter){
stringToConvert.append(a.charAt(iteratorForShorter));
iteratorForShorter++;
}
else{
break;
}
}
if(stringToConvert.length()<32 | iteratorForLonger<b.length()){
String remainingString = b.substring(iteratorForLonger);
stringToConvert.append(remainingString);
}
System.out.println(stringToConvert);
return stringToConvert.toString().getBytes();
}
You can use StringBuilder to achieve this. Please find below source code.
public static void main(String[] args) throws InterruptedException {
int MAX_ALLOWED_LENGTH = 14;
String str1 = "yyyyyyyyyyyyyyyy";
String str2 = "xxxxxx";
StringBuilder builder = new StringBuilder(MAX_ALLOWED_LENGTH);
builder.append(str1);
char[] shortChar = str2.toCharArray();
int index = 2;
for (int charCount = 0; charCount < shortChar.length;) {
if (index < builder.length()) {
// insert 1 character from short string to long string
builder.insert(index, shortChar, charCount, 1);
}
// 2+1 as insertion index is increased after after insertion
index = index + 3;
charCount = charCount + 1;
}
String trimmedString = builder.substring(0, MAX_ALLOWED_LENGTH);
System.out.println(trimmedString);
}
Output
yyxyyxyyxyyxyy
String one = "longwordorsomething";
String two = "short";
String shortString = "";
String longString = "";
if(one.length() > two.length()) {
shortString = two;
longString = one;
} else {
shortString = one;
longString = two;
}
StringBuilder newString = new StringBuilder();
int j = 0;
for(int i = 0; i < shortString.length(); i++) {
if((j + 2) < longString.length()) {
newString.append(longString.substring(j, j + 2));
j += 2;
}
newString.append(shortString.substring(i, i + 1));
}
// Append last part
newString.append(longString.substring(j));
System.out.println(newString);