Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Is it possible from one string (date) generate another fixed length string (5-char code) by some encrypting algorithm for example? Also should be possible to confirm that a output string (5-char code) has been generated using the input string (date)
What I need:
generateCode("10-10-2010") -> "HG45Q"
isCodeValid("HG45Q", "10-10-2010") -> true
Slightly hacky and not tested fully, but seems to do the job. I shall leave you to code the inverse function for validation:
public static String generateCode(String s) {
String result = null;
s = s.replaceAll("\\D", "");
result = new BigInteger(s).toString(36).toUpperCase();
while (result.length() < 5) {
result = "0" + result;
}
return result;
}
class HelloWorld {
public static void main(String[] args) {
System.out.println(toHexString("10-10-2010".getBytes()));
System.out.println();
System.out.println(fromHexString("31302d31302d32303130"));
}
public static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for(int i = 0; i < ba.length; i++)
str.append(String.format("%x", ba[i]));
return str.toString();
}
public static String fromHexString(String hex) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
}
return str.toString();
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 days ago.
Improve this question
Here is the code I thought should work but I am missing something:
public String arrayToString(int[] nums){
String str;
int[] results = new int[nums.length];
for(int i = 0; i < nums.length; i++){
String string = "[1 , 2, 3, 4]";
}
return str;
}
This should return all the values of nums with spaces or do I need to switch the string?
I have tried to use the toString option which for some reason is not allowed in the IDE I am using as it is not using JRE 17 I believe the error message said. So that was not an option since I could not use java.lang.String.
You're actually doing quite nothing to reach your goal, you don't use nums values, and have defined a strange String string = "[1 , 2, 3, 4]";
You need to append all the values of nums to reach your goal, here are some ways
An array-style with existing method
// '[1, 5, 8, 98]'
public static String arrayToString(int[] nums) {
return Arrays.toString(nums);
}
A concatenatde-values style
// '1,5,8,98'
public static String arrayToString(int[] nums) {
StringBuilder result = new StringBuilder();
String separator = "";
for (int num : nums) {
result.append(separator).append(num);
separator = ",";
}
return result.toString();
}
Same with brackets
// '[1,5,8,98]'
public static String arrayToString(int[] nums) {
StringBuilder result = new StringBuilder("[");
String separator = "";
for (int num : nums) {
result.append(separator).append(num);
separator = ",";
}
return result.append("]").toString();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
public class SplitStringobj {
public static void main(String[] args) {
String val1= Start//complete//First//com//upload the dummy123//First//download;
String val2= First;
String[] splitObject = outObject.split("//");
for(String obj :splitObject) {
if(outObject.startsWith(obj.toString());
break;
}
}
}
As i need below O/P
List item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=First
Output=First//com//upload the dummy123//First//download
List item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=complete
Output=complete//First//com//upload the dummy123//First//download
List item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=com
Output=com//upload the dummy123//First//download
Here is my attempt.
public static String first_match(String[] str, String toMatch) {
boolean match = false;
StringBuilder output = new StringBuilder();
for (int i=0; i<str.length; i++) {
if (str[i].equals(toMatch)) {
match = true;
}
if (match){
output.append(str[i]);
if (i != str.length-1) {
output.append("//");
}
}
}
return output.toString();
}
Using the above method for:
String val1 = "Start//complete//First//com//upload//First//download";
String val2 = "First";
String[] splitObject = val1.split("//");
String out = first_match(splitObject, val2);
System.out.println(out);
it gives output:
First//com//upload//First//download
EDIT:
I just realised from the comment that it could be done easier with the following:
public static String firstMatch(String str, String toMatch) {
int index = str.indexOf(toMatch);
if (index == -1) return "";
return str.substring(index);
}
String out1 = firstMatch(val1, val2);
EDIT 2:
And here's another one-liner way.
val1.replaceFirst(".*?" + val2, val2)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to write a code in Java which does make changes to case of a alphabet character in an alternating fashion(either make it lowercase or uppercase)
For Example:
changeCapitalization("hey 123 ABC idk"); // hEy 123 AbC iDk
changeCapitalization("abcdef ghijk 12 abc"); // aBcDeF gHiJk 1 AbC
You can use StringBuilder to build new string and boolean marker to change between lower/upper letter case.
public static String changeCapitalization(String str) {
StringBuilder buf = new StringBuilder(str.length());
boolean upperCase = false;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
buf.append(upperCase ? Character.toUpperCase(ch) : Character.toLowerCase(ch));
upperCase = !upperCase;
} else
buf.append(ch);
}
return buf.toString();
}
public static void main(String[] args) {
String str ="hello THERE";
String new_str="";
for(int i=0;i<str.length();i++){
String c =Character.toString(str.charAt(i));
if(Character.isUpperCase(str.charAt(i))){
c=c.toLowerCase();
new_str+=c;
}
else if(Character.isLowerCase(str.charAt(i))){
c=c.toUpperCase();
new_str+=c;
}
else if(c.equals(" ")){
new_str+=" ";
}
}
System.out.println(str);
System.out.println(new_str);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a class like below
public class EXOR{
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String binAddr[]=new String[18];
for (int i=0;i<18;i++)
{
int x[]=new int[18];
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
System.out.println("binernya : " +binAddr[i]);
}
}
public static void main(String[] args){
new EXOR().conv();
}
}
and I want to convert that array to binary array format.
I want to get output like below
for example
00100100001111110110101010001000
10000111101000110000100011010011
................................
How to fix this problem?
I suppose while executing your code you must've got a number point exception. This occurs when the Hexadecimal string is out of the range of Integer.
You can use:
binAddr[i]= (new BigInteger(Parray[i],16)).toString(2);
instead of
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
This will solve your problem for quick reference
Big Integer Documentation
Code:
public class EXOR {
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String [] binAddr = new String[Parray.length];
for (int i = 0; i < binAddr.length; i++)
{
int strLen = Parray[i].length();
binAddr[i] = "";
for(int j = 0; j < strLen; j++) {
String temp = Integer.toBinaryString(
Integer.parseInt(String.valueOf(
Parray[i].charAt(j)), 16));
// Pad with leading zeroes
for(int k = 0; k < (4 - temp.length()); k++) {
binAddr[i] += "0";
}
binAddr[i] += temp;
}
System.out.println("Original: " + Parray[i]);
System.out.println("Binary: " + binAddr[i]);
}
}
public static void main(String[] args){
conv();
}
}
First few lines of Output:
Original: 243f6a88
Binary: 00100100001111110110101010001000
Original: 85a308d3
Binary: 10000101101000110000100011010011
We have Integer.MAX_VALUE = 2147483647
But, the 2nd item "85A308D3" = 2242054355. It exceed the capability of an Integer.
So, you use Integer.parseInt(85A308D3) will cause java.lang.NumberFormatException.
To fix it, change your code to use Long instead of Integer
binAddr[i] = Long.toBinaryString(Long.parseLong(Parray[i], 16));
Hope this help!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to reverse words in string of java without using split method and StringTokenizer.
For example, How are you must be printed in you are How.
I tried but I failed to do it.
Any help will be appreciated.
Try below code snippet
import java.util.ArrayList;
public class ReverseString
{
public static void main(String args[])
{
String myName = "Here we go";
ArrayList al = new ArrayList();
al = recursiveReverseMethod(myName,al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for(int i = al.size()-1; i>=0;i--)
{
sb.append(al.get(i)+" ");
}
System.out.println(sb);
}
public static ArrayList recursiveReverseMethod(String myName,ArrayList al)
{
int index = myName.indexOf(" ");
al.add(myName.substring(0, index));
myName = myName.substring(index+1);
if(myName.indexOf(" ")==-1)
{
al.add(myName.substring(0));
return al;
}
return recursiveReverseMethod(myName,al);
}
}
Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,
class testers {
public static void main(String[] args) {
String testStr="LongString";
testers u= new testers();
u.reverseStr(testStr);
}
public void reverseStr(String testStr){
char[] d= testStr.toCharArray();
int i;
int length=d.length;
int last_pos;
last_pos=d.length-1;
for (i=0;i<length/2;i++){
char tmp=d[i];
d[i]=d[last_pos-i];
d[last_pos-i]=tmp;
}
System.out.println(d);
}
}
I would do this:
public static String reverseWordsWithoutSplit(String sentence){
if (sentence == null || sentence.isEmpty()) return sentence;
int nextSpaceIndex = 0;
int wordStartIndex = 0;
int length = sentence.length();
StringBuilder reversedSentence = new StringBuilder();
while (nextSpaceIndex > -1){
nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
wordStartIndex = nextSpaceIndex + 1;
}
return reversedSentence.toString();
}