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;
}
Related
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 months ago.
Improve this question
can someone help me with string validation? I tried to find the solution, but none was satisfied.
I have the uri e.g. /dog/cat/house,1/mouse/bird,1/rabbit.
I need to check if after word (with comma) bird, there is a number or not. In my case sometimes i receive uri with number: "bird,1" and sometimes with word: "bird,foo".
Thank you for any suggestions.
As #Federico klez Culloca and #The fourth bird suggested you could use a regular expression (\\bbird,(?:[1-9]|1[0-9]|20)\\b) but some security scans don't like regular expressions. In any case, one another (pure Java) solution would be:
Updated the answer after user added more conditions.
would look for range 1, 2 .. 20 (01, 02 would return false).
public static boolean isNumber() {
// you can parametrize these 2
String input = "/dog/cat/house,1/mouse/bird,10/rabbit.";
String strOfInterest = "/bird,";
boolean isStringEndingInLT20 = false;
int indxOfInterest = input.indexOf("/bird,") + strOfInterest.length();
char c1 = input.charAt(indxOfInterest);
char c2 = input.charAt(indxOfInterest + 1);
int i1 = Character.getNumericValue(input.charAt(indxOfInterest));
if (Character.isDigit(c1) && Character.isDigit(c2)) {
int num = Integer.parseInt("" + c1 + c2);
if ((i1 > 0) && (num >= 1) && (i1 <= 20)) isStringEndingInLT20 = true;
} else if (Character.isDigit(c1)) {
if ((i1 >= 1) && (i1 <= 9)) isStringEndingInLT20 = true;
}
return isStringEndingInLT20;
}
NOTE: I personally hate these verbose solutions and would prefer 1 line REGEX. Try to avoid it and use regex. The only times I avoid regex is when it becomes performance bottleneck and/or causes a security concern.
This is a practical algorithm, you can specify the keyword!
The premise is that the validity of the contains parameter is in line with your description.
keyword, (spaces are allowed)123/
public static void main(String[] args) throws IOException {
String contains = "/dog/cat/house,1/mouse/bird,a/rabbit";
FreeTest f = new FreeTest();
boolean has = f.hasNumber(contains, "bird");
System.out.println(has);
}
/**
* Check if string contains number after specific word
*
* #param contains string contains
* #param key the specific word (without comma)
* #return yes or not
*/
public boolean hasNumber(String contains, String key) {
int commaIndex = contains.indexOf(',', contains.indexOf(key));
int startIndex = commaIndex + 1;
boolean hasNumber = true;
while (true) {
char c = contains.charAt(startIndex++);
if (c == '/') break; // exit
if (c != ' ') {
hasNumber = Character.isDigit(c);
}
}
return hasNumber;
}
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 2 years ago.
Improve this question
for (int i = 0; i < str1.length(); i++)
{
String c = str1.substring(i, i + 1);
for (int j = 0; j < str2.length(); j++)
{
String d = str1.substring(j, j + 1);
if (d != c)
{
System.out.println("no");
}
else
{
System.out.println("yes");
}
}
}
I know this is not even correct but I have no idea how to start.
Do you mean as you would do in the classical introductory programming exercise?
E.g. something like this?
String a = "Hello, world!";
String b = "world";
boolean contained;
contained = false;
for (int i = 0; i < a.length() - b.length() + 1 && !contained; i++) {
contained = true;
for (int j = 0; j < b.length() && contained; j++)
if (a.charAt(i + j) != b.charAt(j))
contained = false;
}
System.out.println(contained ? "b is a substring of a" : "b is not a substring of a");
How can I write a java program to check if a string is a substring of
another string without using indexOf(), contains(), etc?
There are many ways (also based on which functions/methods you use) e.g. the following solution uses String#length and String#equalsIgnoreCase in addition to String#substring (the method which you have already used in your code). The logic checks if the subject substring is equal to (ignoring case) the substring of the same length starting from an index in str.
public class Main {
public static void main(String[] args) {
// Test
System.out.println(isSubstring("World", "Hello World!"));
System.out.println(isSubstring("foo", "Hello World!"));
}
static boolean isSubstring(String substring, String str) {
if (substring == null || str == null) {
return false;
}
int len = substring.length();
for (int i = 0; i <= str.length() - len; i++) {
if (substring.equalsIgnoreCase(str.substring(i, i + len))) {
return true;
}
}
return false;
}
}
Output:
true
false
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;
}
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.