Cut off last half of String - java

I need to cut off half of a user-entered string. I've tried this and it didn't work:
Scanner sc = new Scanner(System.in);
String nameOne = sc.nextLine();
chars[] oneChars = new char[nameOne.length];
double oneLength = oneChars.length / 2;
Math.round(oneLength);
int oneLen = (int)oneLength;
String nameOneFinal = "";
for(int i = 0; i == oneLen--; i++) {
oneChars[i] = oneChars[oneLen];
nameOneFinal = nameOneFinal + oneChars[i];
}

final int mid = nameOne.length() / 2;
String[] parts = {
nameOne.substring(0, mid), // 1st part
nameOne.substring(mid), // 2nd part
};

using substring method ... you can do it
Ex:
public String extraEnd(String str) {
String s = str.substring(str.length()/2);//it will have the last half of string
return s ;
}

Use SubString method to get this
String str = "CutThisBytwo";
int len = str.length();
String firstHalfStr = str.substring(0, len/2);
String secondHalfStr = str.substring(len/2,len );
System.out.println(firstHalfStr);
System.out.println(secondHalfStr);

The easy way: using String.substring(int index1, int index2)
The hard way:
String new = "";
for(int i = 0; (i < old.length() - 1) / 2; i++){
new += old.charAt(i);
}
If it's for a homework, the hard way might get you brownie points, but if not just stick to the easy way.

Related

Binary addition of Strings

I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)
String a = "10110001"
String b = "01101101"
String c = "10101011"
String result = "00100001"
Solution I came up with:
long resultLong = 0;
for( String a : inputs )
{
resultLong = resultLong & Long.parseLong( a ,2);
}
String result = Long.toBinaryString( resultLong );
The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?
If Long is not enough for your use case then you can use BigInteger
BigInteger(String val, int radix);
Which takes a String and radix as the arguments.
BigInteger result = new BigInteger(inputs[0], 2);
for (int i = 1; i < inputs.length; i++) {
result = result.and(new BigInteger(inputs[i], 2));
}
String resultStr = result.toString(2);
Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:
public static void main(String[] args) {
String a = "10110001";
String b = "01101101";
String c = "10101011";
String arr[] = new String[]{a, b, c};
String finalString = "";
for (int i = 0; i < arr[0].length(); i++) {
int temp = Integer.parseInt("" + arr[0].charAt(i));
for (int j = 1; j < arr.length; j++) {
temp = temp & Integer.parseInt("" + arr[j].charAt(i));
}
finalString += temp;
}
System.out.println(finalString);
}
O/P
00100001

How to split a string after 2nd occurrence of dot(.) in java

I have a string which looks something like this(the most basic form):
String str = "1.0.0.190"
The str can be something like this as well:
1.11.0.12 or 2.111.1.190 or 1.0.0.0
I want to split the string at the 2nd occurrence of the dot(.). How can I achieve that ?
Output:
String str = "1.0.0.190"
String output = "1.0"
I'd fit the answer to OP's level, so I wouldn't recommend split or regexps to him...
If you need substring to second dot, simply find second dot and cut the string to that position...
public class DotSubstring {
public static void main(String[] args) {
String s = "1.2.3.4";
int secondDotPosition = findSecondDotPosition(s);
if (secondDotPosition > 0) {
System.out.println(s.substring(0, secondDotPosition));
} else {
System.out.printf("ERROR: there is not a 2nd dot in '%s'%n", s);
}
}
private static int findSecondDotPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == '.') --dotsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
}
The problem with split for beginner is, that is accepts regexp, that's why it is escaped in Joop Eggen's answe like this str.split("\\.").
And yes, that can be achieved in one line as user3458271 wrote in a comment same as xyz later in answer, just error checking would be more difficult (for example if there are no 2 dots...).
In one line with substring and indexOf:
String output = str.substring(0,str.indexOf(".",str.indexOf(".")+1));
public static void main(String[] args) {
String input = "2.111.1.190";
String[] out = input.split("\\.");
String output1 = out[0]+"."+out[1];
System.out.println(output1);
String output2 = "";
for(int x=2; x < out.length; x++)
output2 += out[x] +".";
System.out.println(output2);
}
For the other fields too:
String[] halfs = str.split("\\.");
String[] fulls = new String[halfs.length / 2];
for (int i = 0; i < fulls.length; ++i) {
fulls[i] = halfs[2*i] + "." + halfs[2*i + 1];
}
return fulls[0];
The same technique reduced for the first field:
String[] halfs = str.split("\\.", 3);
return halfs[0] + "." + halfs[1];
Simply:
return str.replaceAll("^([^.]*\\.[^.]*)\\..*$", "$1");

How to check if character at current index in for loop is a specific character (e.g. the letter A, the number 2, etc)?

I'm building a simple program in Java that finds letters in strings and replaces them with a number, but I'm having trouble finding a method that will allow me to check for the exact specific character. There are plenty for digits and letters in general.
As my for loop stands now, it just replaces the letter everywhere, irregardless of whether it is within the range specified by start and end.
Any help would be appreciated.
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
for (int i = start; i < end; i++) {
if (Character.isLetter(str.charAt(i)) {
str = str.replaceAll("A", "9");
return str;
Expected Output:
A.A.9.9.9.A.A.A
Actual Output:
9.9.9.9.9.9.9.9
In your code, you have
str = str.replaceAll("A", "9");
This will replace all the occurrences of A to 9
Instead of your approach, you should
1.Convert the string to a char array
char[] charArray = str.toCharArray();
2.Then replace each occurrence of character with a number
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
3. Convert it back to string using
str = String.valueOf(charArray);
Modified Code:
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
//Converting String to char array
char[] charArray = str.toCharArray();
for (int i = start; i < end; i++) {
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
}
//Converting Back to String
str = String.valueOf(charArray);
System.out.println(charArray);
System.out.println(str);
Compare for character equality and then use string builder to replace the specified character
//Use of StringBuffer preferred over String as String are immutable
StringBuilder sb = new StringBuilder(str);
// -1 to start as index start from 0
for (int i = start-1; i < end; i++) {
char currentChar = currentString.charAt(i);
if (currentChar == "A") {
sb.setCharAt(i, '9');
}
}
return sb.toString();
I'd do it that way. Cut out the string to isolate the part you want to act on, do your replace ans stitch it all back together :
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String beginning = str.substring(0, startIndex);
String middle = str.substring(startIndex, endIndex);
String end = str.substring(endIndex);
middle = middle.replaceAll("A", "9");
String result = beginning + middle + end;
System.out.println(result);
Prints out :
A.A.9.9.9.A.A.A
EDIT:
As suggested in the comments, you could do it in one line
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String result =
str.substring(0, startIndex) +
str.substring(startIndex, endIndex).replaceAll("A", "9") +
str.substring(endIndex);
Here is an example using substrings to let you choose what portion of the string you want to test
int start = 3;
int end = 9;
String str = "A.A.A.A.A.A.A.A";
String startStr = str.substring(0,start);
String endStr = str.substring(end);
String newStr="";
char temp=' ';
for (int i = start; i < end; i++) {
temp = str.charAt(i);
if (temp=='A')
newStr+="9";
else
newStr += temp;
}
return(startStr + newStr + endStr);
You are replacing all the match found in the string and not specifying the index that needs to be replaced.
Use the StringBuffer replace method like below:
public static void main(String[] args) {
String str = "AAAAAAAA";
int start = 3;
int end = 9;
str = replaceBetweenIndexes(str, start, end, "9"); // AAA999AA
str = replaceBetweenIndexes("ABCD6EFG", start, end, "3"); // ABC363FG
}
public static String replaceBetweenIndexes(String str, int start, int end, String replaceWith) {
StringBuffer strBuf = new StringBuffer(str);
for (int i = start; i < end; i++) {
if (Character.isLetter(strBuf.charAt(i)) {
strBuf.replace(i, i+1, replaceWith);
}
}
return strBuf.toString();
}

Java split in jdk 1.3

I get an error for String[] t = words.split("_"); using jdk 1.3 in intelliJ
Error:(133, 51) java: cannot find symbol
symbol: method split(java.lang.String)
location: variable words of type java.lang.String
I have to use this SDK because the project is old, I tried jdk 1.4 but had many other errors, then I decided to replace the above code with something that can be complied using jdk 1.3.
What is the function for that?
The following piece of code seems to be working fine for me.
However, I have assumed that the delimiter on the basis of which you need to split is only a single character.
public static void main(String[] args){
String string = ",alpha,beta,gamma,,delta";
String[] wordsSplit = splitByDelimiter(string, ",");
for(int i=0; i<wordsSplit.length; i++){
System.out.println("-"+wordsSplit[i]+"-");
}
}
public static String[] splitByDelimiter(String fullString, String delimiter){
// Calculate number of words
int index = 0;
int[] delimiterIndices = new int[fullString.length()];
int wordCount = 0;
do{
if(delimiter.equals(fullString.charAt(index)+"")){
delimiterIndices[wordCount++] = index;
}
index++;
} while(index < fullString.length());
// Correction for strings not ending in a delimiter
if(!fullString.endsWith(delimiter)){
delimiterIndices[wordCount++] = fullString.length();
}
// Now create the words array
String words[] = new String[wordCount];
int startIndex = 0;
int endIndex = 0;
for(int i=0; i<wordCount; i++){
endIndex = delimiterIndices[i];
words[i] = fullString.substring(startIndex, endIndex);
startIndex = endIndex+1;
}
return words;
}
Alternate solution:
public static ArrayList splitByDelimiter(String fullString, String delimiter){
fullString += delimiter; //
ArrayList words = new ArrayList();
int startIndex = 0;
int endIndex = fullString.indexOf(delimiter); //returns first occurence
do{
words.add(fullString.substring(startIndex, endIndex));
startIndex = endIndex+1;
endIndex = fullString.indexOf(delimiter, startIndex);
} while(endIndex != -1);
return words;
}
public String[] split(String regex) was introduced in Java 1.4
So you could use your own implementation using StringTokenizer(String str, String delim) which was introduced in Java 1.0
List list = new ArrayList();
StringTokenizer st = new StringTokenizer("this_is_a_test", "_");
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
//[this, is, a, test]
Further if you want final result as an Array, you can use
String[] t = list.toArray(new String[0]);
You will either have to use StringTokenizer, a combination of indexOf() and substring(), or something you make on your own.
You could go with the C approach, which is: implement it yourself.
Here is a possible implementation, it now returns all elements, might need some tweaks:
int length;
int split_amount = 0;
String temp = new String("This_takes_into_consideration_something_something_test");
char split = '_';
for(int i = 0; i<length;i++){
if(temp.charAt(i) == split ){
split_amount++;
}
}
split_amount++;
String[] result = new String[split_amount];
int j = 0;
for(int i = 0; i<split_amount; i++){
result[i] = "";
boolean t = true;
for(; j<length && t ;j++){
if(temp.charAt(j) == split){
t = false;
break;
}
result[i] += temp.charAt(j);
}
j++;
}
Maybe a simple solution is:
String words = "this_is_a_test";
StringTokenizer st0 = new StringTokenizer(words, "_");
String[] t = new String[st0.countTokens()];
int k = 0;
while(st0.hasMoreTokens()){
String tmp0 = st0.nextToken();
t[k] = tmp0;
k++;
}

Dividing a StringBuffer into smaller parts

I have a large stringbuffer which i would like to break into smaller parts. The string buffer looks like this
"name1+name2+name3+name4+..........+name2000"
Where
name1=john
name2=prince
and so on.
(You get the idea.name1,name2,name3 stand for actual names of varying length)
Now i would like to store the names in a string array with each positon containing a 200 names.
string[0]="name1+name2+name3+........+name200";
string[1]="name201+name202+...."
How would i go about achieving this task?
StringTokenizer str = new StringTokenizer(<StringBufferObject>);
int count = 0;
int arrCount = 0;
StringBuffer temp;
String[] stringArr = new String[x];
while(str.hasMoreTokens()) {
count++;
if(count != 200) {
temp.append(str.nextToken());
}
else {
stringArr[arrCount] = temp;
temp.delete(0,temp.length());
count = 0;
arrCount++;
}
It would be a lot easier to split a String using String.split() if that's possible:
/* something like this */
String arrayOfStrings = inputString.split("\+");
If you have to keep it as a StringBuffer you'll have to loop over the input and tokenize it yourself.
I guess it would look something like this:
public String[] getTwoHundredStrings(StringBuffer inputBuff, String someToken)
{
String [] nameArray = new String [200];
int currentPos = 0;
int nextPos = 0;
for ( int i = 0; i < 200; i ++ ) {
nextPos = inputBuff.indexOf(someToken, currentPos);
if ( nextPos < 0 ) {
break;
}
String nextName = inputBuff.substring(currentPos, nextPos);
nameArray[i] = nextName;
currentPos = nextPos;
}
/* do some cleanup if nameArray has less than 200 elements */
return nameArray;
You must have some delimiter between each name. To break the string we should have some delimiter.
If you have delimiter you can use subString() in for loop.
try to use
String[] tempNames = new String(namesBuffer).split("+");
and then
int length = (tempNames.length / 200)+ (tempName.length % 200)
String[] names = new String[length];
for(int i = 0 ; i< tempNames.length ; i++){
for(int j = 0 ; j < length ; j++)
names[j] = tempNames[i];
}
hope this helps
Split on "+", using String.split("\\+")
Get chucks, in smaller arrays, Arrays.copyOfRange(...)
Join using Guava Joiner like Joiner.on("+").join(smallerArray)

Categories