Get Portion of String - java

I need to get the values after "Swap:".
I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.

Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");
index += "Swap:".length();
textContent.subString(index);

Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");
int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
parts[i] = Integer.parseInt(stringParts[i]);
It will fill an integer array will the values after the "Swap" part.

Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {
public ShellOutput() {
final String extract = "Swap:"; // the keyword to search
String shellOutput = "Swap: 75692 29657 0"; // your shell output
int position = shellOutput.indexOf(extract); // get the position of the Swap: text
if (position != -1) {
String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used
int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used
String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number
System.out.println("Total = " + totalNumber);
} else {
System.out.println("No '" + extract + "' segment found.");
}
}
public static void main(String[] args) {
new ShellOutput();
}
}
Output: Total = 75692

Related

java.lang.StringIndexOutOfBoundsException Error while reading Binary String

I have a long String with binary values. And i have a hash map that has the Binary digits as a key and char as a value. I have a function that supposed to read the binary string using 2 pointers and compare with hashmap and store the corresponding char in main.decodedTxt. However, im getting string out of bound exception for this. I don't know how to solve this. I'm getting exception on "String temp =" line. I have a picture link of the console output to see better picture.
public static void bitStringToText (String binText){
String bs = binText;
int from =0;
int to = 1;
while(bs != null){
String temp = bs.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Image of console exception is here
First of all there is no need to check if bs is null because no part of your code changes the value of bs. Your current code will cross the possible index of your binText at some point. It's better to loop just binText and check if you find something within it. After all you have to traverse the complete string anyways. Change your code as follows
public static void bitStringToText (String binText){
//no need to do this if you are not modifying the contents of binText
//String bs = binText;
int from =0;
int to = 1;
int size = binText.length();
String temp = "";
while(to <= size ){
temp = binText.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Hope it helps.
First, give it a try to practice debugging. It is an easy case. Either use run in debug mode (place break point on String temp = bs.substring(from, to); line) or print values of from and to before the same line. It will help to understand what is going on.
Solution:
If bs is not null you will always have StringIndexOutOfBoundsException. Because you are not checking if to is pointing to not existed index of bs String. Easiest example of the first one will be empty String: bs == "".
One of the solution could be to replace condition in while to while (to <= bs.length()).

How to explode a string on a hyphen in Java?

I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.

Add a dot inbetween a string or int to create a double JAVA

I need something to turn somthing like this: 29939299322 into 299392.99322 automatically as it has to do this alot.
i have found things like format but it only seems to be able to add things in front of the number but this has to happen after the sixth number.
preferably from an int directly into a double. but i haven't even found a way t do it from a string.
so if any of u know if this is even possible please help me do this.
and it has to be java. if u also know any documentation which can help me also post it,
thanks in advance
Well, if you are using Strings, you could use regex (Not really efficient but clean and readable:P) :
public static void main(String[] args) {
String s1 = "29939299322";
System.out.println(s1.replaceAll("(\\d{6})(\\d+)", "$1.$2"));
}
O/P :
299392.99322
Code:
public static void main(String args[]) {
int intInput = 123456789; // I am using 123456789 because you want to
// input an integer, and "29939299322" is
// greater than the maximum value for an
// integer: "2147483647"
String input = intInput + ""; // Converts the input into a String
String output = ""; // This is the output String, it will later be
// converted into a double
for (int i = 0; i < input.length(); i++) { // Loops through the input
if (i == input.length() - 5) { // If the index is at the certain
// point in the String...
output += "."; // Adds "."
}
output += input.charAt(i) + ""; // Adds the character into the
// output String after converting it
// into a String
}
double outputDouble = Double.parseDouble(output); // Parses the output
// into a Double
System.out.println(outputDouble); // Outputs Double
}
Output:
1234.56789

Using regex to add a new line to a string every time each line reaches a certain length

I'm trying to ensure text does not appear outside of the window as the window size cannot be changed.
The image above shows what happens when the string of the order numbers exceeds the length of the window. I'm trying to ensure that when the length of the string of order numbers reaches a certain length, I use regex to make a new line for the next orders.
private String listOfOrders( Map<String, List<Integer> > map, String key )
{
String res = "";
if ( map.containsKey( key ))
{
List<Integer> orders = map.get(key);
for ( Integer i : orders )
{
res += " " + i + ",";
}
} else {
res = "-No key-";
}
return res;
}
}
This is the code to display the text, it works by forming the string res and filling it with the order numbers from the array list.
I found, through researching, a cool little piece of code which replaces a string every set amount of characters with itself plus a new line.
if(res.length() >= W-10)
{
res = res.replaceAll("(.{20})", "$1\n");
}
else
{
res += " " + i + ",";
}
But this has no effect at all. And I also realised that this code can not tell how long each line is because I'm using length to determine the length of each line and not how long each line is between each "\n".
My question is, how do I go about using regex to ensure each line in the string is a certain number of characters long? As my attempt does not work. The above just provides context as to why I want lines in a string a certain legnth.
Thanks!

Unexpected Type errors

I'm getting two small unexpected type errors which I'm having trouble trying to solve.
The errors occur at:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Any advice?
public class SwapLetters
{
public static void main(String[] args)
{
System.out.println("Enter a string: ");
String str = new String(args[0]);
String swapped = str;
char[] charArray = str.toCharArray();
System.out.println("Enter a position to swap: ");
int Swap1 = Integer.parseInt(args[1]);
System.out.println("Enter a second position to swap: ");
int Swap2 = Integer.parseInt(args[2]);
char temp1 = str.charAt(Swap1);
char temp2 = str.charAt(Swap2);
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
System.out.println("Original String = " + str);
System.out.println("Swapped String = " + swapped);
}
}
You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).
Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.
Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not
less than the length of this string. Check the length of each string.
The left side of your assignment cannot receive that value.
Description of String#charAt(int):
Returns the char value at the specified index
It returns the value of the character; assigning values to that returned value in the following lines is the problem:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.
Try the following:
String swapped;
if(swap1 > swap2) {
swap1+=swap2;
swap2=swap1-swap2;
swap1-=swap2;
}
if(swap1!=swap2)
swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);

Categories