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

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

Related

Java count how many times a char from string occurs from an array [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 5 years ago.
I'm new to java and I cant find the answer to this problem.
If I have two character arrays like this with counters:
Character[] abc = {'A','B','C'};
int countABC = 0;
Character[] def = {'D','E','F'};
int countDEF = 0;
And a string like this:
String something = "ABCDEFGHABAB";
How to increase the counters?
If you loop through each of the characters in the string and then within the loop use 2 'if' functions, one for each array then you can use the indexOf() function to search an array for that value. If the value is negative then it wasn't found and you don't increase the counter.
Here is some more info on indexOf():
https://www.tutorialspoint.com/java/java_string_indexof.htm

Why does Java 8's split not produce the last token [duplicate]

This question already has answers here:
Java String split removed empty values
(5 answers)
Closed 6 years ago.
I would expect the following Java code to split a string into three items:
String csv = "1,2,";
String[] tokens = csv.split(",");
System.out.println(tokens.length);
However, I am only getting two items.
I must admit that I did not analyze this very deeply, but it seems counter-intuitive to me. Both Python and C# generate three items, as follows, in Python:
def test_split(self):
line = '1,2,'
tokens = line.split(",")
for token in tokens:
print('-' + token)
-1
-2
-
and in C#:
[Test]
public void t()
{
string s = "1,2,";
var tokens = s.Split(',');
foreach (var token in tokens)
{
Console.WriteLine("-" + token);
}
}
-1
-2
-
What am I missing?
This is Java 1.8.0_101.
Use overloaded version of the method:
tokens = line.split(",", -1)
The documentation is clear on this behavior:
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.

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.

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

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)

Reversing a string without using any built in methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing reverse of any String without using any predefined function?
Please advise how to reverse a string without using built in methods. I want to use only string class, please advise let say there is a string "john is a boy" and print "yob a si nhoj".
This method will return the string backwards. all you have to do is iterate through the string backwards and add it to another string.
you do this using a for loop, but first check if the string has a greater lenght than 0.
Java Strings have a method "charAt(index)" which return a single character on the position of the string, where position 0 is the first character. so if you would like to reverse "Boy" you would start on letter 2, then 1, and then 0, and add them all together into a new String, resulting in "yoB".
public static String reverseString(String inString) {
String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
if(inString.length()>0) {//Check the string for a lenght greater than 0
//here we set a number to the strings lenght-1 because we start counting at 0
//and go down to 0 and add the character at that position in the original string to the resulting one
for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
resultString+=inString.charAt(stringCharIndex);
}
}
//finaly return the resulting string.
return resultString;
}
You could iterate through all the characters in your string and prepend them to a StringBuffer using the insert(0, char) method. Then at the end of the iteration, your StringBuffer will be the reversed string.

Categories