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
I want to store all possible substring in String []. I tried this but got an error:
public void sub(String word){
String [] Str=new String[100];
int n=0;
for (int from = 0; from < word.length(); from++) {
for (int to = from + 1; to <= word.length(); to++) {
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
}
}
}
What is solution?
error is: cannot find symbol, variable str, loction: class substring
Well, that fairly clearly tells you what the error is: You haven't declared str. You have declared Str, but Java's identifiers are case sensitive, str and Str are not the same identifier.
So change
String [] Str=new String[100];
to
String [] str=new String[100];
// ^--- lower case
Before, when you hadn't said what the error was, there were a couple of other things Pshemo and I (amongst others) noticed:
You have a sequence issue here:
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
...since you're incrementing n before outputting the string, you're always going to output null. Just moving the increment fixes that:
str[n]=word.substring(from, to);
System.out.println(str[n]);
n++;
Another possible problem can occur for longer words, where number of substrings can be more then 100. In that case you should avoid creating fixed size array, but try using dynamic size collection like List
List<String> str = new ArrayList<String>();
To put or read elements here just use str.add(substring) and str.get(index).
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 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
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 5 years ago.
Improve this question
I'm trying to split a String at every Nth occurence, but missing the last values.Here is what is expected.
Input : String str = "234-236-456-567-678-675-453-564";
Output :
234-236-456
567-678-675
453-564
Here N=3, where the str should be split at every 3rd occurence of -.
Try this.
String str = "234-236-456-567-678-675-453-564";
String[] f = str.split("(?<=\\G.*-.*-.*)-");
System.out.println(Arrays.toString(f));
result:
[234-236-456, 567-678-675, 453-564]
You can try the following with Java 8:
String str = "234-236-456-567-678-675-453-564";
Lists.partition(Lists.newArrayList(str.split("-")), 3)
.stream().map(strings -> strings.stream().collect(Collectors.joining("-")))
.forEach(System.out::println);
Output:
234-236-456
567-678-675
453-564
Maybe one of the worst way without using function available in java , but good like exercise :
public static void main(String[] args){
String s = "234-236-456-567-678-675-453-564";
int nth =0;
int cont =0;
int i=0;
for(;i<s.length();i++){
if(s.charAt(i)=='-')
nth++;
if(nth == 3 || i==s.length()-1){
if(i==s.length()-1) //with this if you preveent to cut the last number
System.out.println(s.substring(cont,i+1));
else
System.out.println(s.substring(cont,i));
nth=0;
cont =i+1;
}
}
}
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
Before you ask, yes I did Google this first. I haven't found a proper answer yet. I understand the syntax for a String array in a for loop, but not for a String. For example, let's say I have a fragment code which includes a for loop that's purpose is to adjust an element of the String to "josh" if that element isn't equal to something (I can't think of anything at the top of my head). The fragment code would be like this:
public void adjustScore(String[] str){
for(int j= 0; j < str.length; j++){
if(str[j] != //idk, something//
str[j]= "josh";
}
else{};
}
But, how would this look if it was a String instead of a String[]?
public void adjustScore(String str2){
for(int j=0; j < str2.length(); j++){
// How do I call an element from the String? Would I still use str2[j]?//
In Java, a String is not an array of characters. Although it is true that the only "elements" in a String are characters, you can use String.charAt(int) to get a character at a valid index (but you cannot use []).
char ch = str2.charAt(j);
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
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.
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 want to find all the substring of one String that contains a key word.
Ex: "This is the keyword in the string".
Output: the keyword, this is the keyword, the keyword in the string, is the keyword in ....
I am think of finding all the substrings first then try to filter one by one. But I think that would be very bad solution.
Could you please give me some advice to do that!. Thank you very much.
I have edited to just find the sequence of tokens.
Try this:
String str = "abcdefkeybncv...";
String key = "key";
int index = str.indexOf(key);
ArrayList<String> sub = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j <= str.length() - i; j++) {
String s = str.substring(i, i+j);
if(s.indexOf(key) >= 0){
sub.add(s);
}
}
}
System.out.println(sub);
Output for the code above:
[abcdefkey, abcdefkeyb, abcdefkeybn, abcdefkeybnc, abcdefkeybncv, abcdefkeybncv., abcdefkeybncv.., abcdefkeybncv..., bcdefkey, bcdefkeyb, bcdefkeybn, bcdefkeybnc, bcdefkeybncv, bcdefkeybncv., bcdefkeybncv.., bcdefkeybncv..., cdefkey, cdefkeyb, cdefkeybn, cdefkeybnc, cdefkeybncv, cdefkeybncv., cdefkeybncv.., cdefkeybncv..., defkey, defkeyb, defkeybn, defkeybnc, defkeybncv, defkeybncv., defkeybncv.., defkeybncv..., efkey, efkeyb, efkeybn, efkeybnc, efkeybncv, efkeybncv., efkeybncv.., efkeybncv..., fkey, fkeyb, fkeybn, fkeybnc, fkeybncv, fkeybncv., fkeybncv.., fkeybncv..., key, keyb, keybn, keybnc, keybncv, keybncv., keybncv.., keybncv...]
Build suffix array: http://en.wikipedia.org/wiki/Suffix_array
Use binary search to find your substring there
Move up and down from this point in suffix array while suffixes starts with substring