How to calculate tab length till the end of the String? [duplicate] - java

This question already has answers here:
Java String split removed empty values
(5 answers)
Closed 8 years ago.
I am spliting the String by tab like
String s = "1"+"\t"+2+"\t"+3+"\t"+"4";
System.out.println("length : "+ s.split("\\t").length);
In this case i get the length 4. But if i remove the last element 4 & give only blank, like
String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);
In this case i got the output 3. it means this is not calculating last tab.
In below case also, i need the length 4. This scenario i am using in my project & getting undesired result.
So please suggest me, How to calculate the entire length of tab delimited string, whether the last element is also blank.
Such as, if the case is,
String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);
then the answer should be 4 & if the case is,
String s = "1"+"\t"+2+"\t"+3+"\t"+"" + "\t"+ "";
System.out.println("Length : "+ s.split("\\t").length);
then the answer should be 5.
Please provide me the appropriate answer.

To prevent split from removing trailing empty spaces you need to use split(String regex, int limit) with negative limit value like
split("\t", -1)

Related

How to substring a String containing 4 bytes characters? [duplicate]

This question already has answers here:
How to get the substring that contains the first N unicode characters in Java
(2 answers)
Closed 5 years ago.
I have a String that could contain 4 bytes characters. For example:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
I also have a size that I should use to get a substring from it. The size is in characters. So let's say that size is 5, so I should get the first 4 bytes character along with "1234".
Directly using substring as s.substring(0, 5) gives the wrong result returning the first character and just "123".
I could manage to get the right result using code points this way:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
StringBuffer buf = new StringBuffer();
long size = 5;
s.codePoints().forEachOrdered(charInt -> {
if(buf.codePoints().count() < size) {
buf.appendCodePoint(charInt);
}
});
I bet there should be a way better and more efficient code to achieve this.
You can use offsetByCodePoints in order to help find the index of the character following 5 code points, and then use that as the second parameter to substring:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
String sub = s.substring(0, s.offsetByCodePoints(0, 5));
Ideone Demo

If statement help (noob) [duplicate]

This question already has answers here:
What's the best way to check if a character is a vowel in Java?
(5 answers)
Closed 6 years ago.
I was trying to grab the first character from user entry, and determine it to be a vowel or not. I am very new, and have been struggling with this for a while. I am trying to add all vowels to the variable 'vowel', and not only will that obviously not work, but I feel like I am going the long way. Any help at all is vastly appreciated as I am very new to this.
entry = scanner.nextLine();
letters = entry.substring(0,1);
holder = entry.substring(1);
vowels = "A";
if (entry.substring(0,1).equals(vowels)) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}
First, since you only want one character, don't use string methods, i.e. use entry.charAt(0) == 'A' instead of entry.substring(0,1).equals("A").
With that, you can then turn it around:
"AEIOU".indexOf(entry.charAt(0))
If the character at position 0 in the entry variable can be found, indexOf() returns the index position (zero-based), otherwise it returns -1.
So, to see if it is a vowel, do this:
if ("AEIOU".indexOf(entry.charAt(0)) != -1) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}

How to add whichever character between every character of a premade String? [duplicate]

This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.

Get Each Character From Output - Java

Right now I have a program that puts an inputted expression into Postfix Evaluation. Below is a copy of my console.
Enter an expression: ((5*2-1)/6+14/3)*(2*3-5)+7/2
5 2 * 1 - 6 / 14 3 / + 2 3 * 5 - * 7 2 / +
I now need to walk through the output, however this output is just a bunch of System.out.print 's put together. I tried using a stringBuilder however it cant tell the difference between 14 and a 1 and 4.
Is there anyway I can go through each character of this output? I need to put these numbers into a stack.
You can use String.split() and if you need only numbers regular expression.
Here is an Example:
public class Test {
public static void main(String[] args) {
String str = "1 * 2 3 / 4 5 6";
String[] arr = str.split(" ", str.length());
for (int i=0;i < arr.length;i++)
System.out.println(arr[i] + "is diggit? " + arr[i].matches("-?\\d+(\\.\\d+)?"));
}
}
str holds the long String. arr will hold the split sub strings.
you just need to make sure that each sub string differ one space from the other.
Well, you deleted your code while I was reading it, but here's a conceptually developed answer.
As you input every character, you want to push that to the stack.
The unique scenario you've mentioned 14 is unique in that it's two characters.
So what you would want to do is track if the last character was ALSO a number.
Here's a rough pseudo. Your stack should be all Strings to support this.
//unique case for digit
if(s.charAt(0).isDigit()) {
//check to see if the String at the top of a stack is a number by peeking at its first character
if(stack.peek().charAt(0).isDigit()) {
int i = Integer.parseInt(stack.pop()) * 10;
//we want to increment the entire String by 10, so a 1 -> 10
i = i + Character.getNumericValue(s.charAt(0)); //add the last digit, so 10 + 4 = 14
stack.push(Integer.toString(i)); //put the thing back on the stack
}
else {
//handle normally
stack.push(s.substring(0,1));
}
}
Is there a reason you need to parse the actual string?
If so, then what you do is, create a StringBuffer or StringBuilder, and wherever you put System.out.print in your code, append the buffer - including the spaces, which are what will help you differentiate between 1 4 and 14. Then you can convert that to a String. Then you can parse the String by splitting it by the spaces. Then iterate through the resulting String array.
If there is no reason for you to use the actual full string, you can instead use a List object and just add to it in the same places in the code. In this case, you don't need the spaces. Then you'll be able to simply iterate through the list.
You'll still be able to print you output - by printing the elements in the list.

Pulling just certain address from href tag in string always ends in .jpg

I have a string that always looks like so:
Site Info
...where sitenum=XXX will be any 3 or 4 or 5 number combo. I am trying to get just the sitenum from this string.
I figured this would give me the correct information for 3 numbers:
String src = de.substring(de.lastIndexOf("sitenum=") + 3);
However, that just takes 'sit' off of the 'sitenum=' and returns everything else like ">Site Info
I would like it to stop after getting the numbers and hitting the " that is found just after the numbers.
Am i using lastIndexOf incorrectly?
EDIT -- Answer worked for one url, but not another:
http://www.wcc.nrcs.usda.gov/cgibin/wygraph-multi.pl?state=NV&wateryear=current&stationidname=19K07S
I am trying to pull 'state' from this url, but it is not pulling state, just replacing letters in 'state'... Here is the code:
String state = de.substring(de.lastIndexOf("state=") + 2,
de.indexOf("&", de.lastIndexOf("state=")));
The state is always a 2 letter or the number 0... When I run this on my string I get:
ate=0
for example... I am confused on how this works?
EDIT EDIT! AH! I get it... so 2 needs to be 6 cause that is the amount of chars I am comparing to find the next char from?
Use this:
String src = de.substring(de.lastIndexOf("sitenum=") + 8,de.indexOf("\"",de.lastIndexOf("sitenum=")));
Not the best way of doing it, but check if it is what you need:
String src = de.substring(de.lastIndexOf("sitenum=") + "sitenum=".length(), de.indexOf(">Site Info") - 1);
Actually you are trying to get the text which is after "sitenum=", but lastIndexOf("sitenum=") will return the starting index of "sitenum=" and not the text which you are expecting
try
int startindex = de.lastIndexOf("sitenum=") + "sitenum=".length();
int endIndex = de.lastIndexOf("\">Site Info</a>");
String src = de.substring(startindex ,endIndex);

Categories