Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to increment by one an String that is only digits:
String current = "000433"; //After increment, will be "000434"
I have this procedure, that works properly:
private String incrementOne(String numberAsString) {
int leftZeroCount = countLeadingZeros(numberAsString);
Integer asInteger = Integer.parseInt(numberAsString);
asInteger++;
return parseStringWithNZeros(asInteger, leftZeroCount);
}
private String parseStringWithNZeros(Integer asInteger, int leftZeroCount) {
String asString = Integer.toString(asInteger);
for (int i = 0; i < leftZeroCount; i++)
asString = "0" + asString;
return asString;
}
private int countLeadingZeros(String numberAsString) {
int count = 0;
int i = 0;
while (numberAsString.charAt(i) == '0' && i < numberAsString.length()) {
count++;
i++;
}
return count;
}
The process is:
Count the left zeros
Parse to Integer
Increment by one
Parse to String
Add the left zeros
The length of the number as String is unknown. I am sure that exists another easier and cleaner way, with regex or something. Which alternatives can I adopt?
Thanks.
How about doing it like this, using String.format():
String original = "000433";
String incremented = String.format("%0" + original.length() + "d",
Integer.parseInt(original) + 1);
System.out.println(incremented);
Try this:
private String incrementOne(String numberAsString) {
int length = numberAsString.length();
Integer asInteger = Integer.parseInt(numberAsString);
asInteger++;
numberAsString = asInteger.toString();
while(numberAsString.length() < length){
numberAsString = "0" + numberAsString;
count ++;
}
return numberAsString;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I need to replace non-digit characters from an array of String and return a String with digits separated by coma, actually, I made it but don't like it.
The first thing I made, was added values from the String array to the String.
Then I replaced non-digit characters from a String.
After that, I added digit values to an int array and sorted it.
Then I added all this stuff to an array of strings and separated values with commas, after that I returned it.
I would be glad for advice, thanks for attention.
import java.util.Arrays;
class Test {
private static String sortedStringOfNumber(String[] string) {
StringBuilder temp = new StringBuilder();
for (String s: string) {
temp.append(s);
}
String numberOnly = temp.toString().replaceAll("[^0-9]", "");
int[] numbers = new int[numberOnly.length()];
for (int i = 0; i < numberOnly.length(); i++) {
numbers[i] = numberOnly.charAt(i) - '0';
}
Arrays.sort(numbers);
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[i] = String.valueOf(numbers[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(result[i].toString());
if (i != result.length - 1)
sb.append(", ");
}
return sb.toString();
}
public static void main(String[] args) {
String[] arrayStringData = new String[] { "1", "ab3c", "level", null, "java2s.com", "asdf 456", "Br0C0de" };
//Should be "0, 0, 1, 2, 3, 4, 5, 6"
System.out.println("Sorted string of numbers ->\t" + sortedStringOfNumber(arrayStringData));
}
}
Your solution would run in O(n*log n) mainly due to Arrays.sort.
Use a simple counting sort. This would give you a runtime of O(n).
Look at the string and ignore all other non-digits.
You might also try it this way:
String sortedIntsCsv = Arrays.stream(string).map(s -> s.replaceAll("\\D", "")).mapToInt(Integer::valueOf).sorted().mapToObj(String::valueOf).collect(Collectors.joining(","));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am looking for solution using stream api for below requirement. basically we need to write a encryption logic to convert a string
aaabbbbaae --> a3b4a2e1
Solution without stream's api :
public static void main(String[] args) {
String sampleString = "aaabbbaaaaaee";
char charters[] = sampleString.toCharArray();
char currentChar = charters[0];
char prevChar = charters[0];
int count = 0;
String str = "";
for (char c : charters) {
if(c==currentChar) {
count++;
prevChar = c;
}
else {
str = str + prevChar + count;
currentChar = c;
count=1;
}
}
System.out.println(str+currentChar+count);
}
This would be pretty easy to do yourself
String encryptToLettersAndNumbers(String input) {
String product = "";
char last = input.charAt(0);
int streak = 0;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == last) {
streak++;
} else {
product = product + last + streak;
streak = 1;
last = input.charAt(i);
}
}
product = product + last + streak;
return product;
}
Note that this code is untested. Furthermore this will be a very unsafe method of encryption because h1e1l2o1 is pretty easy to guess.
This should get you started-
String sampleString = "aaabbbaaaaaee";
Arrays.asList(sampleString.chars().mapToObj(c->(char)c).toArray(Character[]::new)).stream().forEach(c->{
//You can put your logic here to process
System.out.print(c);
});
This will convert your String to a Character list and stream through it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In Oracle :
Case 1:
SELECT INSTR('Viveok Srinivoasamoorthy','o',15,1) FROM DUAL;
Output: 19
Case 2:
SELECT INSTR('Viveok Srinivoasamoorthy','o',15,2) FROM DUAL;
Output: 20
same like, I need to develop a java program with 4 parameter(string, substring, start_position and nthoccurrence) to achieve.
This is the code I tried , but in the below code I can't able to find the nth occurance:
public static int nthoccur(String str1,String str2,int occurs )
{
int f_occurance=0;
f_occurance=str1.indexOf(str2, occurs-1)+1;
System.out.println("f_occurance Value------*** "+f_occurance);
return f_occurance;
}
public static void main(String args[])
{
int resultinst=nthoccur("Viveok Srinivoasamoorthy","o",15);
System.out.println(resultinst);
}
Output:
f_occurance Value------*** 19
19
Now I want to find the 2nd occurrence "o" from 15th position of string using java program. How can I achive the Case 2 using Java program?
Here is a method that should mimic INSTR .
Comments will help you understand how it works, step by step :
public static int instr(final String str, final String substring, int position, final int occurrence) {
// matches counter
int count = 0;
// index of last match
int indexFound = 0;
// while we haven't reached the desired match count, and we still find another match
while (count != occurrence && (indexFound = str.indexOf(substring, position)) != -1)
{
// increment match count
count++;
// position the next search index, to the end of the current match
position = indexFound + substring.length();
}
if (count == occurrence) {
// the number of occurrences was matched, return the last match index
return indexFound + 1; // index in Java starts at 0
} else {
// the number of occurrences was not matched, return 0
return 0;
}
}
here is one more way : -1 means no occurence.
getInstring(String input, String substr, int start, int occurence) {
char[] tempstring = input.substring(start).replaceAll(substr, "-").toCharArray();
int occurindex = 0;
int counter = 0;
for (int i = 0; i < tempstring.length; i++) {
if (":-".equals(":" + tempstring[i])) {
occurindex++;
counter = i;
}
if (occurindex == occurence) {
break;
}
}
return counter == 0 ? -1 : counter + start + 1;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
import java.util.StringTokenizer;
public class PigLatins {
String str1;
int vowelIndex;
String[] vowels = {"a","e","i","o","u","A","E","I","O","U"};
String counter = "";
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
}
At this part result[x].substring(1,vowelIndex) in the if statement, it seems to return null, why is it wrong and how could I fix it? (I removed the driver class as stackoverflow told me to I had too much code)
You should change :
for(int i = 0;i<vowels[i].length();i++)
to
for(int i = 0;i<vowels.length;i++)
Since you want to iterate over all the vowels in the array.
vowels[i].length() will always give you 1, since it's the length of the i'th String in the vowels array.
Beside that, it would make more sense to change the vowels array from String[] to char[].
the problem here is that the vowelIndex is 0 while you start in index 1 for the substring.
i don't quite understand what you are trying to achive but you need to check in you if statement the value of vowelIndex:
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i]))
the whole function should be
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
also you should not use an array of strings of you need an array of charecters, or if i understand correctly you should use a set of charecters
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find the number of substrings in a given string. Currently, My code doesn't take account of over lapping strings.
For example
substr = "cde"
str = "cdcde"
My code:
public static int ssCount(String str, String substr) {
int count = 0;
int strlen = str.length();
int substrlen = substr.length();
int numsubstr = 0;
int substrpointer = 0;
for (int i = 0; i < strlen; i++) {
if (str.charAt(i) == substr.charAt(substrpointer)) {
substrpointer++;
count++;
}
else {
count = 0;
substrpointer = 0;
}
if (count == substrlen) {
numsubstr++;
count = 0;
}
}
return numsubstr;
}
My attempt:
public static int ssCount(String str, String substr) {
int count = 0;
int strlen = str.length();
int substrlen = substr.length();
int numsubstr = 0;
int substrpointer = 0;
int firstchar = 0;
for (int i = 0; i < strlen; i++) {
if (str.charAt(i) == substr.charAt(substrpointer)) {
substrpointer++;
count++;
if (str.charAt(i) == substr.charAt(0)) {
firstchar = i;
}
}
else {
count = 0;
substrpointer = 0;
i = firstchar;
}
if (count == substrlen) {
numsubstr++;
count = 0;
}
}
return numsubstr;
}
I tried to add a 2nd pointer that will point to the next occurrence of the first character of the substring in order to continue the comparisons from that spot. However I am having trouble because I can run into some infinite loops.
This finds all overlapping sub-strings in a larger string. The non-regex way followed by the regex way. An interesting problem.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P>{#code java OverlappingSubstringsXmpl}</P>
**/
public class OverlappingSubstringsXmpl {
public static final void main(String[] igno_red) {
String sToFind = "cdc";
String sToSearch = "cdcdcdedcdc";
System.out.println("Non regex way:");
int iMinIdx = 0;
while(iMinIdx <= (sToSearch.length() - sToFind.length())) {
int iIdxFound = sToSearch.indexOf(sToFind, iMinIdx);
if(iIdxFound == -1) {
break;
}
System.out.println(sToFind + " found at index " + iIdxFound);
iMinIdx = iIdxFound + 1;
}
System.out.println("Regex way:");
Matcher m = Pattern.compile(sToFind, Pattern.LITERAL).matcher(sToSearch);
boolean bFound = m.find();
while (bFound) {
System.out.println(sToFind + " found at index " + m.start());
bFound = m.find(m.start() + 1);
}
}
}
Output:
[C:\java_code\]java OverlappingSubstringsXmpl
Non regex way:
cdc found at index 0
cdc found at index 2
cdc found at index 8
Regex way:
cdc found at index 0
cdc found at index 2
cdc found at index 8
Not sure what your question is, probably how to fix your code, but my recommendation is to look into standard approaches to solving this problem, such as the KMP algorithm. It efficiently takes into account overlaps too.