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
Two methods of implementing a string. A counted string explicitly
records its length. The terminated string’s length is determined by an
end-of-string mark.
Can anyone give an example of counted string and a terminated string in java.
CountedString {
char[] string;
int length;
int getLength() {
return length;
}
}
TerminatedString {
char[] string;
final static char TERMINATOR = '$';
int getLength() {
for (int i = 0; i < string.length; i++) {
if (string[i] == TERMINATOR) return i;
}
}
}
If you look in to the String.java will find that the length of String is being calculated by counter which traverse through string's characters .
Please referString.java for more information. You should look in to this class to see implementation of length() method.
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 2 years ago.
Improve this question
For event handling how can you check a string that has a combination of integers and a character?
For example - 1234p
If the user enters the example above, how can you check if the user enters integers first and then a character at the end? What kind of exception will be thrown if the data type input is not an integer or char?
You can use REGEX [0-9]+[a-zA-Z] to match if the string contains chars and integers otherwise throw an IllegalArgumentException
public void check(String input) {
if (!input.matches("[0-9]+[a-zA-Z]")) {
throw IllegalArgumentException("Not valid string");
}
// do other logic
}
So from your question it sounds like you expect a string that has all numbers except the last character that has to be an alphabet. You can check if the given string matches this condition the following way too:
String string = "1234p";
int length = string.length();
boolean numsFirst = string.substring(0, length - 1).chars().allMatch(x -> Character.isDigit(x));
boolean lastChar = Character.isDigit(string.charAt(length - 1));
if(numsFirst && lastChar)
return true;
else
return false;
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
A program that takes the first two characters of a string and adds them to the front and back of the string. Which version is better?
public String front22(String str) {
if(str.length()>2) return str.substring(0,2)+str+str.substring(0,2);
return str+str+str;
}
or
public String front22(String str) {
// First figure the number of chars to take
int take = 2;
if (take > str.length()) {
take = str.length();
}
String front = str.substring(0, take);
return front + str + front;
}
The former strikes me as more elegant. The latter is easier to understand. Any other suggestions for improvement of either is more than welcome!
Issue with the first option, mainly because string is immutable. [Edit.] As #Pshemo correctly pointed out, my statement was unclear. Quoting #Pshemo, "executing same substring twice is inefficient when we can reuse result from first substring".
Use a StringBuilder.
StringBuilder sb = new StringBuilder(str);
CharSequence seq = sb.subSequence(0,2);
sb.insert(0, seq);
sb.append(seq);
return sb.toString();
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