I want to divide a string like this:
String = "Titanic";
into two strings of equal length, and if it isn't divisible by 2 it will have 1 letter or extra on first or second part. like this
//if dividle by 2
Str1 = "BikG";
Str2 = "amer";
//if it isnt dividle by 2
Str1 = "Tita";
Str2 = "nic";
You can do it for example like this:
String base = "somestring";
int half = base.length() % 2 == 0 ? base.length()/2 : base.length()/2 + 1;
String first = base.substring(0, half);
String second = base.substring(half);
Simply when n is the string's length, if n is divisible by 2, split the string in n/2, otherwise split in n/2 + 1 so that first substring is one character longer than second.
What do you do to divide an odd number e.g. 15 with the same requirement?
You store the result of 15 / 2 into an int variable say
int half = 15 / 2
which gives you 7. As per your requirement, you need to add 1 to half to make the first half (i.e. 8) and the remaining half will be 15 - 8 = 7.
On the other hand, in case of an even number, you simply divide it by 2 to have two halves.
You have to apply the same logic in the case of a String as well. Given below is a demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int half;
String str1 = "Titanic";
half = str1.length() / 2;
String str1Part1 = str1.substring(0, half + 1);
String str1Part2 = str1.substring(half + 1);
System.out.println(str1Part1 + ", " + str1Part2);
String str2 = "HelloWorld";
half = str2.length() / 2;
String str2Part1 = str2.substring(0, half);
String str2Part2 = str2.substring(half);
System.out.println(str2Part1 + ", " + str2Part2);
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a string: ");
String str = in.nextLine();
half = str.length() / 2;
System.out.println(str.length() % 2 == 1 ? str.substring(0, half + 1) + ", " + str.substring(half + 1)
: str.substring(0, half) + ", " + str.substring(half));
System.out.print("Enter Y to continue or any input to exit: ");
} while (in.nextLine().toUpperCase().equals("Y"));
}
}
A sample run:
Tita, nic
Hello, World
Enter a string: Arvind
Arv, ind
Would you like to continue? [Y/N]: y
Enter a string: Kumar
Kum, ar
Would you like to continue? [Y/N]: Y
Enter a string: Avinash
Avin, ash
Would you like to continue? [Y/N]: n
Note:
% is a modulo operator.
Check String substring​(int beginIndex, int endIndex) and String substring​(int beginIndex) to learn more about substring functions of String.
Check https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html to learn about the ternary operator.
You could use String.substring() for this purpose:
String s = "Titanic";
int half = (s.length()+1)/2;
String part1 = s.substring(0, half);
String part2 = s.substring(half);
System.out.println(part1); // Prints: Tita
System.out.println(part2); // Prints: nic
Here (s.length()+1)/2 will auto-truncate 0.5 if it occurs because the division is between ints.
Related
I'm trying to return the middle 3 characters of a word using the substring method but how do I return the middle 3 letters of a word if the word can be any size (ODD only)?
My code looks like this.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputWord;
inputWord = scnr.next();
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring(2,5));
}
}
The reason I have a 2 and 5 in the substring method is because I have tried it with the word "puzzled" and it returned the middle three letters as it was supposed to do. But if I try, for instance "xxxtoyxxx", It prints out "xto" instead of "toy".
P.S. Please don't bash me I'm new to coding :)
Consider the following code:
String str = originalString.substring(startingPoint, startingPoint + length)
To determine the startingPoint, we need to find the middle of the String and go back half the number of characters as the length we want to retrieve (in your case 3):
int startingPoint = (str.length() / 2) - (length / 2);
You could even build a helper method for this:
private String getMiddleString(String str, int length) {
if (str.length() <= length) {
return str;
}
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
Complete Example:
class Sample {
public static void main(String[] args) {
String text = "car";
System.out.println(getMiddleString(text, 3));
}
private static String getMiddleString(String str, int length) {
// Just return the entire string if the length is greater than or equal to the size of the String
if (str.length() <= length) {
return str;
}
// Determine the starting point of the text. We need first find the midpoint of the String and then go back
// x spaces (which is half of the length we want to get.
final int startingPoint = (str.length() / 2) - (length / 2);
return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}
}
Here, I've put the output in [] brackets to reflect any spaces that may exist. The output of the above example is: [ppl]
Using this dynamic approach will allow you to run the same method on any length of String. For example, if our text String is "This is a much longer String..." our output would be: [ lo]
Considerations:
What if the input text has an even number of characters, but the length is odd? You would need to determine if you want to round the length up/down or return a slightly off-center set of characters.
I think what you can do is to calculate the string length then divided by 2. This gives you the string in the middle, then you can subtract one to the start and add 2 to the end. If you want to get the first two for an odd string, then subtract 2 to the start index and add 1 to the end.
String word_length = inputWord.length()/2;
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring((word_length-1, word_length+2));
Hope this helps.
This will get the middle of the string, and return the characters at the middle, and +- 1 from the middle index.
public static String getMiddleThree(String str) {
int position, length;
if (str.length() % 2 == 0) {
position = str.length() / 2 - 1;
length = 2;
} else {
position = str.length() / 2;
length = 1;
}
int start = position >= 1 ? position - 1 : position;
return str.substring(start, position + 1);
}
The work left you have to do is make sure the end position is not greater than the length of the string, otherwise, choose the position as the final index
I have been searching for solution to find strings like this howareyou in sentence and remove them from it. For example:
We have a sentence - Hello there, how are you?
And compound - how are you
As a result I want to have this string - Hello there, ? With compound removed.
My current solution is splitting string into words and checking if compound contains each word, but it's not working well, because if you have other words that match that compound they will also be removed, e.g.:
If we will look for foreseenfuture in this string - I have foreseen future for all of you, then, according to my solution for will also be removed, because it is inside of compound.
Code
String[] words = text.split("[^a-zA-Z]");
String compound = "foreseenfuture";
int startIndex = -1;
int endIndex = -1;
for(String word : words){
if(compound.contains(word)){
if(startIndex == -1){
startIndex = text.indexOf(word);
}
endIndex = text.indexOf(word) + word.length() - 1;
}
}
if(startIndex != -1 && endIndex != -1){
text = text.substring(0, startIndex) + "" + text.substring(endIndex + 1, text.length() - 1);
}
So, is there any other way to solve this?
I'm going to assume that when you compound you only remove whitespace. So with this assumption "for,seen future. for seen future" would become "for,seen future. " since the comma breaks up the other compound. In this case then this should work:
String example1 = "how are you?";
String example2 = "how, are you... here?";
String example3 = "Madam, how are you finding the accommodations?";
String example4 = "how are you how are you how are you taco";
String compound = "howareyou";
StringBuilder compoundRegexBuilder = new StringBuilder();
//This matches to a word boundary before the first word
compoundRegexBuilder.append("\\b");
// inserts each character into the regex
for(int i = 0; i < compound.length(); i++) {
compoundRegexBuilder.append(compound.charAt(i));
// between each letter there could be any amount of whitespace
if(i<compound.length()-1) {
compoundRegexBuilder.append("\\s*");
}
}
// Makes sure the last word isn't part of a larger word
compoundRegexBuilder.append("\\b");
String compoundRegex = compoundRegexBuilder.toString();
System.out.println(compoundRegex);
System.out.println("Example 1:\n" + example1 + "\n" + example1.replaceAll(compoundRegex, ""));
System.out.println("\nExample 2:\n" + example2 + "\n" + example2.replaceAll(compoundRegex, ""));
System.out.println("\nExample 3:\n" + example3 + "\n" + example3.replaceAll(compoundRegex, ""));
System.out.println("\nExample 4:\n" + example4 + "\n" + example4.replaceAll(compoundRegex, ""));
The output is as follows:
\bh\s*o\s*w\s*a\s*r\s*e\s*y\s*o\s*u\b
Example 1:
how are you?
?
Example 2:
how, are you... here?
how, are you... here?
Example 3:
Madam, how are you finding the accommodations?
Madam, finding the accommodations?
Example 4:
how are you how are you how are you taco
taco
You can also use this to match any other alpha-numeric compound.
I have a given String that represents the age in format:
"YY yr MM mo" or
"Y yr MM mo" or
"YY yr M mo" or
"Y yr M mo"
where YY/Y represent years (example: 5 or 44) and MM/M represent months (example: 2 or 11). Just to be clear, I give example of a String pAge = "11 yr 5 mo" or String pAge = "4 yr 10 mo".
Now I'd like to split this String and print it only as a numbers in a two separate text fields that represents years and months in age.
To get years I writing a function:
String arr[] = pAge.split(" ", 2);
return arr[0];
And another function to get months:
int i = pAge.indexOf("yr", pAge.indexOf(" ") + 1);
int k = pAge.indexOf(" ", pAge.indexOf(" ") + 4);
String s = pAge.substring(i, k);
return s.substring(s.lastIndexOf(" ") + 1);
So, first method looks nice and it's easy but is there is any simpler way to write the second function? Both are working well and giving a correct output.
All the 4 cases given by you are the same. All of them have 4 parts delimited by a space.
This means that you can use .split() for all 4 cases:
String[] tokens = pAge.split(" ");
int years = Integer.parseInt(tokens[0]); //get first token
int months = Integer.parseInt(tokens[2]); //get third token
How about this untested pseudo code:
String tokens[] = pAge.split(" ");
if (tokens.length != 4 || tokens[1] != "yr" || tokens[3] != "mo")
throw new SyntaxError("pAge is not 'N yr N mo'");
String years = tokens[0];
String month = tokens[2];
I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction
I'm getting a number from an addition of Int and then put it as String. I need to know what is the first, second etc. number of the addition. For example the number is 7654, how to know that "7" is the first number? And "6" the second? etc.
String result += "\nThe result of addition"
+ String.valueOf(add_1) + "+" + String.valueOf(add_2)
"+ is" + String.valueOf(int_result);
I want to know the number of a determinate position of the String that contain the result.
The string is String.valueOf(int_result), I can use directly int_result too.
Thanks!
Just walk each character in the resulting string:
String result = String.valueOf(int_result);
for (int i=0; i< result.length(); i++) {
char c = result.charAt(i);
System.out.println("Digit " + i + " = " + c);
// And if you need this as an integer
int digit = Integer.parseInt(""+c);
}
In Java to get the character at a particular position in a string just use this
String number ="7564";
char c = number.charAt(0);
The above code will asign '5' to char variable c. You can further parse it to integer by doing this
int i = Integer.parseInt(c);