for(int i=0;i<5;i++)
{
char ans = s.next().charAt(i);
}
I am getting a StringIndexOutOfBoundsException. Why it is happening?
Because s.next() is returning a String with less than 5 characters. Try printing out s.next() to see the value if you expected it to be longer.
You are getting the exception cause you are trying to assign a char in your "ans" variable which is not available. The reason behind this is, the string you're getting by calling the 's.next()' method is not returning a string with at least 5 characters. Let's say the string is "Me" and you're trying to loop through it 5 times where there is only two characters. So when you're trying to look for the 3rd indexed character there is none and so you're getting the "StringIndexOutOfBoundsException"......
You can also re-use the Scanner object, there's no need to create a new one for each user input.
And: "charCount = charCount++;" --> "charCount++;"
Related
Im trying to figure out how to find the end of a string. I'm able to get to the first number in the string that i want (the 6), but I cant figure out how count to the end of the string </td>.My thought is if i can figure how how far it is from the 6 to the closing bracket,I can then substring to get the number 6586.97. Is that correct thinking?
example string <td>6586.97 Lots</td>
Daniel, thank you for your reply. This is what i love about coding. There are a number of ways to get the job done. I had come up with a solution late last night and will post it here.
Count=0;
for (int i =0 ; i<20; i++){
VOL1=StringSubstr(data,string_pos+112+i+string_length,1);
if(VOL1!="/")Count++;
else{Answer=StringSubstr(data,string_pos+112+string_length,Count-6);}}
return(Answer);
What i did was, starting at the 6 i just kept moving to the right till i found the forward slash. Then StringSubstr back.
Use StringFind() to detect start of the message that starts with ">" and end of the message (space bar) and do not forget to start looking for end after start. StringSubstr() is to cut the string that you need
string getStringFromTag(const string example){
int starts = StringFind(example,">");
if(starts>0){
int ends = StringFind(example," ",starts+1);
if(ends>0){
string result=StringSubstr(starts+1,ends-starts-1);
return result;
}
}
return NULL;}
I tried using padEnd() twice on a String. The first time the padEnd() extension function works as expected, but the second time, it does not add the any characters I tried.
My code:
var s = "Hi -> "
s = s.padEnd(10, 'O')
s = s.padEnd(5, ' ')
println(s)
My output:
Hi -> OOOO
I am using kotlin version 1.2.50. I also tried Jetbrains' online compiler to prevent the bug being only on my computer, with the same result. I also tried using a different version of kotlin (1.0.7 and 1.1.60), with still the same feature/bug.
I also tried using the padStart(), with the same behaviour, just adding it in front of the String.
Mixing the two extension functions also did not work as expected: Using padStart() and immediately after that padEnd()
Is this an expected feature? If so why is it expected? Or is it just a bug?
padEnd doesn't add the given character to your String the given number of times - the first parameter is the target length that it will pad up to. From the docs:
Returns a char sequence of length at least length consisting of this char sequence appended with padChar as many times as are necessary to reach that length.
So in your second call, you're trying to pad "Hi -> 0000" until it's at least 5 characters long - which it already is, so no spaces are added at its end.
You could also do something like:
val outerChar = "*"
val x = outerChar.padEnd(10)
.plus("hello")
.plus(outerChar.padStart(10))
println(x)
// Prints:
// * hello *
This will put 10 spaces between the * and hello on each side. Also try swapping the calls to padEnd and padStart.
I have a boolean function that evaluates a 1d array of characters. It has two parameters: a 1d array of characters , and a char c. I want the function to return true if the given char c appears at least four consecutive times within the given array, otherwise it will return false.
I don't know how to start or complete this function at all. Please help! Thanks.
I hope I'm not doing you're homework for you ;). So here's the sudo-code for this problem to help you get started
The first thing you would want is the method header that returns a boolean, and has a parameter for an array of characters and a char
The next step would be to create a counter and run a loop to sift threw every character in the array. Every time you encounter that specific character in the array you would add one to the counter, if the next character isn't the one you want then you would reset the counter to 0. Then add a conditional in the loop to check if the counter reaches 4, if so you would return true. If it never reaches 4 then you would want to return false. Go ahead and try to code that up and see if you get it.
Simple problem. If this is your homework then you shouldn't be doing this. Your question needs to be changed. Firstly give it a try before asking and then once you are done trying you can post the errors or the snippets of codes that you are unsure of and then ask for help. Else you are not going to learn anything. Got a simple solution to your problems. I'm not going to give you the complete solution but instead a guide to help you with your question.
In my opinion string is always a better choice to use instead of char because of the functions that come with that package. Char is just plain old annoying (again in my opinion) unless your question or whatever you are doing this program for requires you to use char.
First,
Create your main program -> create your array and initialize it if you want or you can prompt the user for their input. whichever works.
use the "bool" data type to create your Boolean variable.
Prompt the user to input the char value to check for.
Now call the function and provide the parameters. I'm guessing the function is where you are stuck with so i'm going to provide you the snippets from the code that i wrote for this question.
bool check(char* <array_name>, char* <array_name>) //for the array list and the
//value to check for
{
int size;
size = strlen(<array_name>); //to get the size of the array (array list)
int counter=0; //to keep count of the occurrence of the char to check
for(int x=0; x<size; x++) //ar = array list and token = char to check
{
if(ar[x]==token[0]) //check for each iteration if token is in ar[x]
counter++; //if it is then counter increases by 1
else
counter = 0; //To reset the value to 0 if its not consecutive.
if(counter == 4) //to stop the loop when 4 consecutive values has been found.
break;
}
if(counter >= 4) //as per your requirement 4 or above
return true;
else
return false;
}
EDIT: This is to check the values just until 4 consecutive values of what you are searching for is found and to end the loop. If you want it in a different way then please feel free to comment on this answer. You can always add another counter or anything at all to check how many consecutive times the value is found. For example 1,1,1,1,2,3,4,1,1,1,1,2,3,4,1,1,1,1,2,3,4.
The counter for that will be 3 since it happens 3 times with each time repeating the same value for 4 times consecutively.
If this is your homework then you better study properly because it's a really simple problem and your shouldn't be asking for a solution but instead ask for guidance and try first.
Good luck! If you need further clarification or help just comment on this.
I am trying to read a tag from XML and then want to concatenate a number to it.
Firstly, I am saving the value of the string to a variable and trying to concatenate it
with the variable in the for loop. But it throws an error.
for i = 0:tag.getLength-1
node = tag.item(i);
disp([node.getTextContent]);
str=node.getTextContent;
str= strcat(str, num2str(i))
new_loads = cat(2,loads,[node.getTextContent]);
end
Error thrown is
Operands to the || and && operators must be
convertible to logical scalar values.
Error in strcat (line 83)
if ~isempty(str) && (str(end) == 0 ||
isspace(str(end)))
Error in SMERCGUI>pushbutton1_Callback (line 182)
str= strcat(str,' morning')
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in SMERCGUI (line 44)
gui_mainfcn(gui_State, varargin{:});
Error in
#(hObject,eventdata)SMERCGUI('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
The error suggests that your string is not a string. It's not clear to me whether it's throwing an error at the strcat line, or at the later cat line.
At any rate, it should be clear that you cannot concatenate elements of different types into an array - cell array yes, regular array no. So the line
new_loads = cat(2,loads,[node.getTextContent]);
is bound to give a problem. 2 is numerical, and node.getTextContent is a string - or maybe a cell array or something else. I can't see what loads is, so I can't tell if that is involved in the problem.
Usually a good way to combine numbers and strings into a single string is
newString = sprintf('%s %d', oldString, number);
You can then use all the formatting tricks of printf to produce output exactly as you want. But before you do anything, make sure you understand the type of all the elements you are trying to string together. The easiest way to do this for all the elements in memory is
whos
Or if you just want it for one variable,
whos str
Or all variables starting with s:
whos s*
The output is self-explanatory. If you still can't figure it out after this, leave a comment and I'll try to help you out.
EDIT based on what I read at http://blogs.mathworks.com/community/2010/11/01/xml-and-matlab-navigating-a-tree/ , it is possible that you just need to cast your str variable to a Matlab string (apparently it's a java.lang.string). So try to add
str = char(str);
before using str. It may be what you need.
This question already has answers here:
Is there an easy way to return a string repeated X number of times?
(21 answers)
Closed 9 years ago.
Just a curiosity I was investigating.
The matter: simply repeating (multiplying, someone would say) a string/character n times.
I know there is Enumerable.Repeat for this aim, but I was trying to do this without it.
LINQ in this case seems pretty useless, because in a query like
from X in "s" select X
the string "s" is being explored and so X is a char. The same is with extension methods, because for example "s".Aggregate(blablabla) would again work on just the character 's', not the string itself. For repeating the string something "external" would be needed, so I thought lambdas and delegates, but it can't be done without declaring a variable to assign the delegate/lambda expression to.
So something like defining a function and calling it inline:
( (a)=>{return " "+a;} )("a");
or
delegate(string a){return " "+a}(" ");
would give a "without name" error (and so no recursion, AFAIK, even by passing a possible lambda/delegate as a parameter), and in the end couldn't even be created by C# because of its limitations.
It could be that I'm watching this thing from the wrong perspective. Any ideas?
This is just an experiment, I don't care about performances, about memory use... Just that it is one line and sort of autonomous. Maybe one could do something with Copy/CopyTo, or casting it to some other collection, I don't know. Reflection is accepted too.
To repeat a character n-times you would not use Enumerable.Repeat but just this string constructor:
string str = new string('X', 10);
To repeat a string i don't know anything better than using string.Join and Enumerable.Repeat
string foo = "Foo";
string str = string.Join("", Enumerable.Repeat(foo, 10));
edit: you could use string.Concat instead if you need no separator:
string str = string.Concat( Enumerable.Repeat(foo, 10) );
If you're trying to repeat a string, rather than a character, a simple way would be to use the StringBuilder.Insert method, which takes an insertion index and a count for the number of repetitions to use:
var sb = new StringBuilder();
sb.Insert(0, "hi!", 5);
Console.WriteLine(sb.ToString());
Otherwise, to repeat a single character, use the string constructor as I've mentioned in the comments for the similar question here. For example:
string result = new String('-', 5); // -----
For the sake of completeness, it's worth noting that StringBuilder provides an overloaded Append method that can repeat a character, but has no such overload for strings (which is where the Insert method comes in). I would prefer the string constructor to the StringBuilder if that's all I was interested in doing. However, if I was already working with a StringBuilder, it might make sense to use the Append method to benefit from some chaining. Here's a contrived example to demonstrate:
var sb = new StringBuilder("This item is ");
sb.Insert(sb.Length, "very ", 2) // insert at the end to append
.Append('*', 3)
.Append("special")
.Append('*', 3);
Console.WriteLine(sb.ToString()); // This item is very very ***special***