Getting a displayed line from a large string - java

What I want to do is to measure the data of a line on a large string. I am not sure if any has tried this but I have a string which looks like this.
String a =
"This is
kinda
my String"
which would display on android textview as
This is
kinda
my String
Now what I want to achieve is being able get the length of the second line "kinda".
The purpose for this is to be able to set my paging for a book project.
I hope I was clear enough. Thanks for any advice or ideas shared.

Should just be:
a.split("\n")[1].length()

You can use the String function split(String regex)
To split on a "\n"(newline) then use it as a tuple/array and call for any word you want.

Split based on new line indicator.
String lines[] = a.split("\\r?\\n");
int length =0;
if(lines.length >1)
{
length = lines[1].length();
}

I haven't used java in years that being said I'd imagine something like this
String[] temp; //Let's make an array of strings
temp = a.split("\n"); //Split the large string by carriage return
int length = temp[1].length(); //get the length of the 2nd string
Assuming those are \n separating your lines...

Related

Deleting content of every string after first empty space

How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));

Confused regarding split in Java

I am trying to take a text from a file, and take the a's and b's out using split function.
String inStr = in.readLine();
// for example "a1a1a1a1b"
String lettersStr = letters.readLine();
// for example "ab"
Then i'm doing this trying to split all the letters i want.
Why is this not working?
String outFinal = "\"\\\\s*["+ lettersStr +"]\\\\s*\"";
String[] inSplit = inStr.split(outFinal);
What i'm trying to accomplish is
inStr.split("\\s*[ab]\\s*"));
Which works fine but the problem is that since i'm using a BufferedReader (fileread) the letters to cut out keep changing, hence why i can't just use the line above.
Thanks in advance
Regards
Change
String outFinal = "\"\\\\s*["+ lettersStr +"]\\\\s*\"";
to
String outFinal = "\\s*["+ lettersStr +"]\\s*";

How to convert String input into int and push into a Stack

for example, i have the string "12,456,544,233" from the user input,
I want to take each number that is separated by commas and push each one into
a Stack, converting it to an int in the process because the Stack is .
(array implementation of a stack by the way)
So 12 would be at 0, 456 at 1, 544 at 2, etc...
I KNOW I have to use the Integer class to parse, but just not sure how to setup the loop to do everything, if i didn't provide enough info, ask and I will do so!
thanks.
The code I tried:
String input = scan.nextLine();
stack.push(Integer.parseInt(String.valueOf(input.charAt(2))));
Sounds like homework. so just giving some hints
you can use String.split method to split the string into tokens separated by commas
now traverse the array that you get after split and push to stack.
N.B. if it is really a homework then may be you need to implement your own split
Here is how you can split strings
String string = "12,456,544,233";
String[] individualStrings = string.split(",");
split() method Splits this string around matches of the given regular expression.
Next, you can interate over string array and convert each element into integer.
for(int i = 0; i < individualStrings.length; i++)
{
int m = Integer.parseInt(individualStrings[i]);
}
Cheers !!

Split a String In Java against the split rule?

I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);

How to get perticular digits from the string in android?

I have one String = GETMSG_m_m_5556 from this I want to read only 5556, means I want to read all the digits after last "_". The string has not fixed length of numbers it may be like, GETMSG_m_m_9898786589 OR GETMSG_m_m_98987865. So how can I read the numbers after "_"?
Can anyone suggest me the write way.? It may be foolish question but I am stuck on this. I cant get any idea about this.
Thanks in advance.
String digits = sampleString.subString(sampleString.lastIndexOf("_"),sampleString.lenght);
Get the last index of the char '_' in your string and make a required substring to get the numbers .see string.subString()
You can use the string.split() function and take last string.
String[] separated = yourString.split("_");
// Now choose the last array value
You can try using StringTokenizer
StringTokenizer st = new StringTokenizer(String);
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.startsWith("_")) {
....
}}

Categories

Resources