I have the following code to split a String of a list of words separated by spaces. The string is split and used to populate the array. If I use the .length method, will it return the amount of split strings? As in, would it be similar to the String.length method that counts the amount of characters and returns that value?
I want to have the program increment the array position by one each time it's run, but I want it to reset to 0 if it already used the last word, so it circles back and starts with the first word again.
Would this bit of code reset the word position to 0 when it has already used the last word in the array?
String wordsList[] = words.split(" ");
this.currentWord = wordsList[wordPos];
if(wordPos < wordsList.length)
wordPos++;
else
wordPos = 0;
If you use array.length on an array doesn't it tell you what the length is?
The answer is yes. Also, the .length is a property and not a method.
Take a look at this going over the .length property with a bit more detail. Cheers.
If I understand correctly, It sounds like you want to use a for loop like this?:
String words = "Blah blarg bloob"
String wordsList[] = words.split(" ");
String currentWord = "";
for (int i = 0; i < wordsList.length; i++){
if (currentWord !=null && currentWord.equals(wordsList[i])) {i = 0;}
currentWord = wordsList[i];
}
Related
I have an array, which I use a for each loop to iterate through. I then store it in a string and then try to add a comma to it, but am struggling look for a "logic" based solution.
I am almost close to about 1 year's worth of Java under my belt, so most of the solutions I am trying to find to implement are mostly logic based (for now), since this is apart of Java MOOC's course. What are some options I can look at? What am I missing?
for(int number: array){
String thread = "";
thread += number + ", ";
System.out.print(thread);
}
You can use a Stream to achieve this result.
System.out.println(Arrays.stream(array).collect(Collectors.joining(",")));
I'm not sure the constraints of this project for your course, but if you're able, try a StringJoiner! It will add a delimiter automatically to separate items that are added to it. Another note, I think you're going to want to declare your String outside of your for loop. otherwise it resets every iteration.
StringJoiner joiner = new StringJoiner(",");
for(int number : array){
joiner.add(String.valueOf(number));
}
System.out.print(joiner.toString());
What I like to do when I'm just doing something simple and quick is this:
String thread = "";
for (int i = 0; i < array.length; i++) {
int number = array[i];
thread += number;
if (i < array.length - 1) {
thread += ", ";
}
}
Basically all it does is check that we aren't on the last index and append the comma only if it isn't the last index. It's quick, simple, and doesn't require any other classes.
Pressuming you had a string ending with a comma, followed by zero or more white spaces you could do the following. String.replaceAll() uses a regular expression to detect the replacement part.
\\s* means 0 or more white spaces
$ means at the end of the line
String str = "a, a, b,c, ";
str = str.replaceAll(",\\s*$","");
Prints
a, a, b,c
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
I'm working on a while-loop which should check a text and see if letters are in CAPS or not as well as if they are vowels etc. I'm not sure of how to create a variable which can store certain letters. I asked this question yesterday an was told to use Array, but im wondering theres anyway to do this with help of Strings,charAt.
You can do this without a loop :-
String s = "HELLO";
if(s.toUpperCase().equals(s)){
System.out.println("String is All-CAPS!");
}
Yes you can just iterate over the String with charAt() for every position. If you have a String text:
for(int i = 0; i < text.length() ; i++){
char currentChar = text.charAt(i);
doSomething(currentChar);
}
I am reading from a file and on one of the lines within the file reads:
"{a,b,c,d}" I ran a split function on that line which returned a string array of 10(not sure why 10 instead of 9) elements. Each element being one character long. I then did a foreach loop over that array and within the body of that loop, I am doing a check to see if that "char" is a letterOrDigit and if it is.. do something else. But Within the first iteration of that loop, I get a StringIndexOutOfBounds Exception and for the life of me I do not know Why. I did not run into this issue while using intelliJ. This is being ran in eclipse and it's driving me nuts. Please help.
for(int line = 1; line < file.size(); line++) // start at line 1 cause the line with the alphabet is useless.
{
if(line == 1) // Line 1 is always the states... so create the states.
{
String[] array = file.get(line).split("");
for(String str :array) // split returns a string Array. each element is is one char long
{
// we only care about the letters and not the '{' or the ','
if (Character.isLetterOrDigit(str.charAt(0))) {
dfa.addState(new State(str.charAt(0)));
}
}
}
This is a screenshot of what the String array looks like after the split
This is what the line looks like after the file has been read.
The first string in the array is an empty string: "". It has a length of 0 so str.charAt(0) is out of bounds.
I think you don't need to use spilt function, you want to read whole stuff char by char just like array access.
Empty value to string split function produces extra element because spilt function has no special case handling for such case, although it does handle case properly when length of split string is 1
You can rewrite your code something thing below
for (int line = 1; line < file.size(); line++) // start at line 1 cause the line with the alphabet is useless.
{
if (line == 1) // Line 1 is always the states... so create the states.
{
String lineValue = file.get(line);
int len = lineValue.length();
for (int index = 0; index < len; index++) {
if (Character.isLetterOrDigit(lineValue.charAt(index))) {
//dfa.addState(new State(str.charAt(0)));
}
}
}
}
From your screenshot, the array element at the index 0's length is 0, i.e it's a empty String, but during iteration you're trying to access the first char of empty String, so it throws the IndexOutOfBoundException.
To avoid this check the length or isEmpty before accessing it's char
I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!