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 1 year ago.
Improve this question
Can someone help and explain whether indexOf("") returns 0 is predefined same as -1 by returning a negative result?
Thanks and Happy Easter to all!
ps. the following link was helpful, but it does not contain the exact answer to my question
"Hello".indexOf("") returns 0
public class ExIndexOf {
public static void main(String[] args) {
String s = "We learn Java.";
System.out.println(s.indexOf("ava")); // -> 10
System.out.println(s.indexOf("java")); // -1
System.out.println(s.indexOf(" ")); // -> 2
System.out.println(s.indexOf("")); // -> 0
}
}
Because indexOf returns the first position (index) of its argument in the string. Strings in Java, like arrays and collections are zero-indexed, meaning that the index 0 describes the first item. Index 1 is the second item and index n describes the n+1th item. Many functions return the (invalid) index -1 (a "magic" value) to denote "not found" or "error".
The empty string is contained in every string multiple times. The first position where it can be found is at position 0. Think of it as: String s = "" + "We learn Java." (or even more verbose: s = "" + "W" + "" + "e" + "" + " " + "" + "l" + …).
String s = "We learn Java.";
System.out.println(s.indexOf("")); // -> 0
System.out.println(s.indexOf("W")); // 0
System.out.println(s.indexOf("e")); // -> 1
System.out.println(s.indexOf(" ")); // -> 2
System.out.println(s.indexOf("not found")); // -> -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 3 years ago.
Improve this question
How can I rewrite this code in Java 8 stream API?
public static void main(String[] args) {
final List<String> ids = Arrays.asList("001", "007", "012", "099", "101", "167");
int total = 0;
for (String id : ids) {
if (id.indexOf("1") >= 0) {
System.out.println(id);
total++;
}
}
System.out.println("Total count: " + total);
}
The equivalent stream can be like so :
long total = ids.stream()
.filter(id - > id.indexOf("1") >= 0)
.peek(System.out::println)
.count();
We can do it like :
System.out.println(
"Total count: " + ids.stream()
.filter(id -> id.indexOf("1") >= 0)
.peek(System.out::println)
.count());
It might be even simpler:
long count = Arrays.stream(new String[] {"001", "007", "012", "099", "101", "167"})
.filter(id -> id.contains("1"))
.peek(System.out::println)
.count();
I'd rather have a short break with the condition. The statement id -> id.indexOf("1") >= 0 means that the "1" is contained in the given string at any position, therefore the following expression using String::contains would me more suitable:
.filter(id -> id.contains("1"))
On the other hand, I feel you might want to count these ids having "1" at the first position, therefore String::startsWith is better:
.filter(id -> id.startsWith("1"))
In any case, you have your answer already here.
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 3 years ago.
Improve this question
public static int countX(String str) {
if (str.length() == 0) {
return 0;
}
if (str.charAt(0) == 'x') {
return 1 + countX(str.substring(1));
} else {
return countX(str.substring(1));
}
}
Given an input String of "xxx", the method above shall return 3.
I understand the flow of the method, the line "return 1 + countX(str.substring(1));" adds one if an 'x' is found. What I don't understand is how does that return value carry over to the next iteration/recursion? I don't see the value of the increment stored anywhere.
Look at the line return 1 + countX(str.substring(1));
Now suppose that str was "xx", so the substring passed to the recursive call is "x".
So in that call, since the first character is 'x', it again executes
return 1 + countX(str.substring(1));
in the next recursive call, the substring is empty, so it returns zero to the previous call, which then returns (1+0) to its previous call, which returns ( 1 + (1 +0) ) to the initial call of the method, so the result for the String "xx" becomes 1+1+0 = 2.
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 5 years ago.
Improve this question
For example if:
String str = "100101010";
Then following should happen:
a[0]=1
a[1]=0
a[2]=0
...
It should hold for large strings also (up to 64 characters).
One hint: find a chart for ASCII. http://www.asciitable.com/index/asciifull.gif The code for "0" is 48 and the code for "1" is 49. You can convert characters to numbers just by subtracting 48 from the ASCII value.
int value = str.charAt(0) - 48;
It's important to realize that a Java char is just an integer type just like int and byte. You can do math with them. With that idea in mind, you should be able figure out the rest yourself.
(This is technically a duplicate since I answered a similar question long ago, but I can't find it, so you get a freebie.)
public static int[] getAsArray(String value){
// not null ; not empty ; contains only 0 and 1
if(value == null || value.trim().length()<1 || !value.matches("[0-1]+")){
return new int[0];
}
//if it necessary !value.matches("[0-1]+" regex to validate
value = value.trim();
value = value.length()>64 ? value.substring(0,63) : value;// up to 64 characters
int[] valueAsInt = new int[value.trim().length()];
for (int i = 0 ;i<value.length();i++){
valueAsInt[i]=(int)value.toCharArray()[i]-48;
}
return valueAsInt;
}
also if it's possible use shor or byte type as it's enoght to store 0,1 and you consume less memory as with int
I don't know why you want to do this, but it is a simple problem.
public static void main (String[] args) {
String s = "111232";
String element[] = s.split("");
System.out.println(element[0]);
System.out.println(element[1]);
System.out.println(element[2]);
System.out.println(element[3]);
System.out.println(element[4]);
System.out.println(element[5]);
}
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 8 years ago.
Improve this question
This is homework. I get the logic but i got stuck on the code. I've done it with normally way and it takes 1 week to get the code. I need to get repeat string with recursive way in Java.
This is my code :
static String repeatString (final int n, final String[] syllables, final String currentWord) {
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
repeatString(n - 1, syllables, currentWord + syllables[i]);
}
}
return "";
}
if i call in main method like
String[] str = {"a", "b"};
repeatString(1, str, " ");
then i get output (a,b) if i change to
repeatString(2,str," ");
then i get output ( aa,ab,ba,bb) if i change to
repeatString(3,str," ");
then i get output (aaa,aab,aba,abb,baa,bab,bba,bbb) and so on.
So basically it is like 2 to the power to n. If n=1, i got 2, if n=3, i got 8, and so on.
I would be grateful if someone can help me to get this code in recursive way.
Any help is much appreciated.
The method you have there is recursive already. Being recursive does NOT mean it should have no for loops. A recursive method in cheap words means the method calls itself, which yours does.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to write a program to print all possible permutations with 8 variables where each variable has multiple choices.
For eg. i have
A = {"A1"} //has only one choice
B = {"B1", "B2", "B3", "B4"} // has 4 choices
C = {"C1", "C2"} //has 2 choices
:
:
I = {"I1", "I2", "I3", "I4"} //has 4 choices
My output should be of the form: A-B-C-D-E-F-G-H-I with all possible choices of each variable and the order should be the same.
A1-B1-C1-D1-E1-F1-G1-H1-I1
A1-B2-C1-D1-E1-F1-G1-H1-I1
A1-B3-C1-D1-E1-F1-G1-H1-I1
A1-B4-C1-D1-E1-F1-G1-H1-I1
A1-B1-C2-D1-E1-F1-G1-H1-I1
etc.
I looked at all the other questions here, but i'm not able to figure out if i can use the inbuilt java permutations class for this. I tried writing a recursive program but am stuck when trying to explode each choice into all possible outputs. Appreciate any tips on how to accomplish this in either java/c++/vba since the language is not a consideration. Thanks!
You can write a series of 9 nested loops that does the job in a straightforward way. This would be a mess, though, and it can be done more simply with recursion on the nesting level. (Don't try recursing on the data at each level; that's pointless.) Here's a Java solution in pseudocode:
String[][] DATA = {A, B, ..., I};
void printAll(int recursionLevel, String prefix) {
String[] level = DATA[recursionLevel];
if (recursionLevel == DATA.length - 1) {
// last level -- actually do the output
for (String val : level) {
System.out.println(prefix + "-" + val);
}
} else {
// recurse
if (prefix.length() > 0) {
prefix += "-";
}
for (String val : level) {
printAll(recursionLevel + 1, prefix + val);
}
}
}
You would generate the output by calling:
printAll(0, "");