String str = "Aardvark";
str.indexOf('a');
I was wondering what index str would return if it asked for a certain character and the string contained multiple of it. For example, aardvark: would the method return index 0, for the first instance it saw the char? There are 3 'a' chars in the word, so which would it return?
One additional question (couldn't fit it in the original question)
What is the difference between
str.indexOf('a');
and
str.indexOf("a");
I know the first is a char and the second is a String, but if str = "Aardvark", wouldn't the second statement return -1 or some sort of error, because "a" refers to a single-character String, not one char of a string?
I'm very sorry if this was unclear, I couldn't really think of a better way to pose my question. Thanks in advance!
indexOf() will return the index of the first occurrence of the string/char
like you say, one looks for a char and the other on a sub string. "a" will be found, as "a" is a substring of "Aardvark"
It would print the first occurence..
To get the second occurence you
would have to
fill in
indexOf(char c, int lookafterfirstindex);
indexOf can also take those two parameters instead of just the char.
Link to API Doc:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
Here is a simple example:
String text = "abcd_a";
System.out.println("Index of a: "+ text.indexOf('a')); // Index of a: 0
System.out.println("Index of a: "+ text.indexOf("a")); // Index of a: 0
System.out.println("Index of b: "+ text.indexOf('b')); // Index of b: 1
System.out.println("Index of c: "+ text.indexOf('c')); // Index of c: 2
System.out.println("Index of z: "+ text.indexOf('z')); // Index of z: -1
simple index of:
indexOf(char/string) will always return the first index of the occurrence.
from index:
There is also indexOf(char/string, int fromIndex) - which will search from a given position in your string.
last index:
There is a lastIndexOf(char/string) - which will search last occurrence.
Regarding the char vs String, I would use char if I only need one char index lookup. The char will peform much faster than the String index-lookup-methods!!!
Java String Spec
Related
This question already has answers here:
Java program to find the character that appears the most number of times in a String?
(8 answers)
Closed 6 years ago.
I got a task from my university today:
Write a program that reads a ( short ) text from the user and prints the so called max letter (most common character in string) , that the letter which the greatest number of occurrences of the given text .
Here it is enough to look at English letters (A- Z) , and not differentiate between uppercase and lowercase letters in the count of the number of occurrences .
For example, if : text = " Ada bada " so should the print show the most common character, this example it would be a.
This is an introductory course, so in this submission we do not need to use the " scanner - class" . We have not gone through this so much.
The program will use the show message input two get the text from user .
Info: The program shall not use while loop ( true / false ) , "return " statement / "break " statement .
I've been struggling with how I can get char values into a table.. am I correct I need to use array to search for most common character? I think I need to use the binarySearch, but that only supports int not char.
I'll be happy for any answers. hint's and solutions. etc.. if you're very kind a full working program, but again please don't use the things I have written down in the "info" section above.
My code:
String text = showInputDialog("Write a short text: ");
//format string to char
String a = text;
char c = a.charAt(4);
/*with this layout it collects number 4 character in the text and print out.
* I could as always go with many char c... but that wouldn't be a clean program * code.. I think I need to make it into a for-loop.. I have only worked with * *for-loops with numbers, not char (letters).. Help? :)
*/
out.print( text + "\n" + c)
//each letter into 1 char, into table
//search for most used letter
Here's the common logic:
split your string into chars
loop over the chars
store the occurrences in a hash, putting the letter as key and occurrences as value
return the highest value in the hash
As how to split string into chars, etc., you can use Google. :)
Here's a similar question.
There's a common program asked to write in schools to calculate the frequency of a letter in a given String. The only thing you gotta do here is find which letter has the maximum frequency. Here's a code that illustrates it:
String s <--- value entered by user
char max_alpha=' '; int max_freq=0, ct=0;
char c;
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
for(int j=0;j<s.length();j++){
if(s.charAt(j)==c)
ct++;
} //for j
}
if(ct>max_freq){
max_freq=ct;
max_alpha=c;
}
ct=0;
s=s.replace(c,'*');
}
System.out.println("Letter appearing maximum times is "+max_alpha);
System.out.println(max_alpha+" appears "+max_freq+" times");
NOTE: This program presumes that all characters in the string are in the same case, i.e., uppercase or lowercase. You can convert the string to a particular case just after getting the input.
I guess this is not a good assigment, if you are unsure about how to start. I wish you for having better teachers!
So you have a text, as:
String text = showInputDialog("Write a short text: ");
The next thing is to have a loop which goes trough each letter of this text, and gets each char of it:
for (int i=0;i<text.length();i++) {
char c=text.charAt(i);
}
Then comes the calculation. The easiest thing is to use a hashMap. I am unsure if this is a good topic for a beginners course, so I guess a more beginner friendly solution would be a better fit.
Make an array of integers - this is the "table" you are referring to.
Each item in the array will correspond to the occurrance of one letter, e.g. histogram[0] will count how many "A", histogram[1] will count how many "B" you have found.
int[] histogram = new int[26]; // assume English alphabet only
for (int i=0;i<histogram.length;i++) {
histogram[i]=0;
}
for (int i=0;i<text.length();i++) {
char c=Character.toUppercase(text.charAt(i));
if ((c>=65) && (c<=90)) {
// it is a letter, histogram[0] contains occurrences of "A", etc.
histogram[c-65]=histogram[c-65]+1;
}
}
Then finally find the biggest occurrence with a for loop...
int candidate=0;
int max=0;
for (int i=0;i<histogram.length;i++) {
if (histogram[i]>max) {
// this has higher occurrence than our previous candidate
max=histogram[i];
candidate=i; // this is the index of char, i.e. 0 if A has the max occurrence
}
}
And print the result:
System.out.println(Character.toString((char)(candidate+65));
Note how messy this all comes as we use ASCII codes, and only letters... Not to mention that this solution does not work at all for non-English texts.
If you have the power of generics and hashmaps, and know some more string functions, this mess can be simplified as:
String text = showInputDialog("Write a short text: ");
Map<Char,Integer> histogram=new HashMap<Char,Integer>();
for (int i=0;i<text.length();i++) {
char c=text.toUppercase().charAt(i));
if (histogram.containsKey(c)) {
// we know this letter, increment its occurrence
int occurrence=histogram.get(c);
histogram.put(c,occurrence+1);
}
else {
// we dunno this letter yet, it is the first occurrence
histogram.put(c,1);
}
}
char candidate=' ';
int max=0;
for (Char c:histogram.keySet()) {
if (histogram.get(c)>max) {
// this has higher occurrence than our previous candidate
max=histogram.get(c);
candidate=c; // this is the char itself
}
}
System.out.println(c);
small print: i didn't run this code but it shall be ok.
Below is a String and I want to get the bold id from it.
String s = "> Index1 is: 261 String is: href: https://www.clover.com/v3/merchants/4B8BF3Y5NJH7P/orders/K0AH5696MRG6J?access_token=4ffcfacefd3b2e9611a448da68fff91f, id: **K0AH5696MRG6J**, currency: USD, title: Greta , note: This is test ,";
int ind = s.indexOf("id:");
s = s.substring(ind,s.indexOf(","));
It gives an error index out of bound.
I know that error is there because in substring(int,int) the second parameter value is not correct.
I am trying to get the substring between id: and ,.
Any help
You are getting an IndexOutOfBoundsException because substring found that end index was less than the begin index.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Your initial indexOf call finds the id: properly, but the call to s.indexOf(",") finds the first , in the string, which happens to be before id:.
Use an overload of indexOf that takes a second argument - the index at which to starting looking.
s = s.substring(ind,s.indexOf(",", ind));
I suggest you use
s.indexOf(",", ind)
to get the comma which is after the id: rather than the first one in the String.
If you haven't read all the methods in String yet, I suggest you do as you will be using this class again, and again.
your "," index is before your "id:" index. You must search , after id
// Search id:
int ind = s.indexOf("id:");
// After that: search comma
int comma = s.indexOf(",", ind +1);
this explains this sort of problems:
How to use substring and indexOf for a String with repeating characters?
I am having trouble counting the length of my String which has some surrogate characters in it ?
my String is,
String val1 = "\u5B66\uD8F0\uDE30";
The problem is, \uD8F0\uDE30 is one character not two, so the length of the String should be 2.
but when I am calculating the length of my String as val1.length() it gives 3 as output, which is totally wrong. how can I fix the problem and get the actual length of the String?
You can use codePointCount(beginIndex, endIndex) to count the number of code points in your String instead of using length().
val1.codePointCount(0, val1.length())
See the following example,
String val1 = "\u5B66\uD8F0\uDE30";
System.out.println("character count: " + val1.length());
System.out.println("code points: "+ val1.codePointCount(0, val1.length()));
output
character count: 3
code points: 2
FYI, you cannot print individual surrogate characters from a String using charAt() either.
In order to print individual supplementary character from a String use codePointAt and offsetByCodePoints(index, codePointOffset), like this,
for (int i =0; i<val1.codePointCount(0, val1.length()); i++)
System.out.println("character at " + i + ": "+ val1.codePointAt(val1.offsetByCodePoints(0, i)));
}
gives,
character at 0: 23398
character at 1: 311856
for Java 8
You can use val1.codePoints(), which returns an IntStream of all code points in the sequence.
Since you are interested in length of your String, use,
val1.codePoints().count();
to print code points,
val1.codePoints().forEach(a -> System.out.println(a));
I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield
I have to write a program that takes string argument s and integer argument k and prints out all subsequences of s of length k. For example if I have
subSequence("abcd", 3);
the output should be
abc abd acd bcd
I would like guidance. No code, please!
Thanks in advance.
Update:
I was thinking to use this pseudocode:
Start with an empty string
Append the first letter to the string
Append the second letter
Append the third letter
Print the so-far build substring - base case
Return the second letter
Append the fourth letter
Print the substring - base case
Return the first letter
Append the third letter
Append the fourth letter
Print the substring - base case
Return third letter
Append the second letter
Append the third letter
Append the fourth letter
Print the substring - base case
Return the third letter
Return the second letter
Append the third letter
Append the fourth letter
Return third letter
Return fourth letter
Return third letter
Return second letter
Return first letter
The different indent means going deeper in the recursive calls.
(In response to Diego Sevilla):
Following your suggestion:
private String SSet = "";
private String subSequence(String s, int substr_length){
if(k == 0){
return SSet;
}
else{
for(int i = 0; i < substr_length; i++){
subString += s.charAt(i);
subSequence(s.substring(i+1), k-1);
}
}
return SSet;
}
}
As you include "recursion" as a tag, I'll try to explain you the strategy for the solution. The recursive function should be a function like that you show:
subSequence(string, substr_length)
that actually returns a Set of (sub)-strings. Note how the problem could be divided in sub-problems that are apt to recursion. Each subSequence(string, substr_length) should:
Start with an empty substring set, that we call SSet.
Do a loop from 0 to the length of the string minus substr_length
In each loop position i, you take string[i] as the beginning character, and call recursively to subSequence(string[i+1..length], substr_length - 1) (here the .. imply an index range into the string, so you have to create the substring using these indices). That recursive call to subSequence will return all the strings of size substr_length -1. You have to prepend to all those substrings the character you selected (in this case string[i]), and add all of them to the SSet set.
Just return the constructed SSet. This one will contain all the substrings.
Of course, this process is highly optimizable (for example using dynamic programming storing all the substrings of length i), but you get the idea.
So, I see you want to implement a method: subSequence(s, n): Which returns a collection of all character character combinations from s of length n, such that ordering is preserved.
In the spirit of your desire to not provide you with code, I assume you would prefer no pseudo-code either. So, I will explain my suggested approach in a narrative fashion, leaving the translation to procedural code as an exercise-to-the-reader(TM).
Think of this problem where you are obtaining all combinations of character positions, which could be represented as an array of bits (a.k.a. flags). So where s="abcd" and n=3 (as in your example), all combinations could be represented as follows:
1110 = abc
1101 = abd
1011 = acd
0111 = bcd
Note, that we start with a bit-field where all characters are turned "on" and then shift the "off" bit over by 1. Things get interesting in an example where n < length(s) - 1. For example, say s="abcd" and n=2. Then we have:
1100 = ab
1001 = ad
1010 = ac
0110 = bc
0101 = bd
0011 = cd
The recursion comes into play when you analyze a sub set of the bit-fields. Hence, a recursive call would reduce the size of the bit-field and "bottom-out" where you have three flags:
100
010
001
The bulk of the work is a recursive approach to find all of the bit-fields. Once you have them, the positions of each bit can be used as an index in the the array of characters (that is s).
This should be sufficient to get you started on some pseudo-code!
The problem is precisely this:
Given an ordered set S : {C0, C1, C2, ..., Cn}, derive all ordered subsets S', where each member of S' is a member of S, and relative order of {S':Cj, S':Cj+1} is equivalent to relative order {S:Ci, S:Ci+d} where S':Cj = S:Ci and S':Cj+1 = S:Ci+d. |S|>=|S'|.
Assume/assert size of set S, |S| is >= the size of the subset, |S'|
If |S| - |S'| = d, then you know each of the subsets S' begins with digit at Si, where 0 < i < d.
e.g given S:{a, b, d, c} and |S'| = 3
d = 1
S' sets begin with 'a' (S:0), and 'b' (S:1).
So we see the problem is actually to solve d lexically ordered permutations of length 3 of subsets of S.
#d=0: get l.o.permutations of length 3 for {a, b, c, d}
#d=1: get l.o.permutations of length 3 for {b, c, d}
#d=2: d > |S|-|S'|. STOP.
string subSeqString() {
string s1="hackerrank";
string s="hhaacckkekraraannk";
int k=0,c=0;
int size=s1.size();
for(int i=0;i<size;i++)
{
for(int j=k;j<s.size();j++)
{
if(s1[i]==s[j])
{
c++;
k++;
break;
}
k++;
}
}
if(c==size)
return "YES";
else
return "NO";
}