Split with specials character and print string value [closed] - java

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)

Related

String representation of all values of nums, with the values separated by spaces [closed]

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();
}

How to generate fixed length string from another string [closed]

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();
}
}

Change the case of every alternate char [closed]

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);
}

Program to reverse the words in a string [closed]

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 7 years ago.
Improve this question
I have written a program to reverse the words in a string.
if i/p is "The dog is chasing"
then o/p should be "chasing is dog The"
public class String_reverse {
public static void main(String[] args) {
String input= "The dog is chasing";
String[] arr= input.split(" ");
String reverse="";
for(int i=arr.length-1;i>=0;i--)
{
reverse+= ((reverse.equals(""))?"":" ")+arr[i];
}
System.out.println(reverse);
}
}
But I don't know how to write this program using recursion. When I tried searching in stackoverflow, I could find reversing a string; but not reversing the words in a string.
Recursive method, using same logic as linked "duplicate", without use of split():
private static String reverseWords(String text) {
int idx = text.indexOf(' ');
return (idx == -1 ? text : reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx));
}
The logic is:
Take first char/word
If that is last char/word, return with it
Perform recursive call with remaining text (excluding word-separating space).
Append space (if doing word)
Append first char/word from step 1
Return result
As you can see, when applied to reversing text (characters) instead of words, it's very similar:
private static String reverseText(String text) {
return (text.length() <= 1 ? text : reverseText(text.substring(1)) + text.charAt(0));
}
For people who like things spelled out, and dislike the ternary operator, here are the long versions, with extra braces and support for null values:
private static String reverseWords(String text) {
if (text == null) {
return null;
}
int idx = text.indexOf(' ');
if (idx == -1) {
return text;
}
return reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx);
}
private static String reverseText(String text) {
if (text == null || text.length() <= 1) {
return text;
}
return reverseText(text.substring(1)) + text.charAt(0);
}
Notice how the long version of reverseText() is exactly like the version in the linked duplicate.
Recursive methods could seem a bit hard when beginning but try to do the following :
Simplify the problem as much as possible to find yourself with the less complicated case to solve. (Here for example, you could use a sentence with two words).
Begin with doing it on a paper, use Pseudocode to help you dealing with the problem with the simplest language possible.
Begin to code and do not forget an escape to your recursion.
Solution
public static void main(String[] args) {
String s = reverseSentence("This sentence will be reversed - I swear".split(" "));
System.out.println(s);
}
public static String reverseSentence(String[] sentence){
if (sentence.length <= 1){
return sentence[0];
}
String[] newArray = new String[sentence.length-1];
for (int i = 0 ; i < newArray.length ; i++){
newArray[i] = sentence[i];
}
return sentence[sentence.length-1] + " " + reverseSentence(newArray);
}
This is a sample program which will do what you want recursively:
public class ReverseWords {
public static void main(String args[]) {
String s = "This is a test";
reverse(s);
}
private static void reverse(String s) {
if(s == null) return;
String words[] = s.split(" ", 2);
if (words.length < 2) reverse(null);
else reverse(words[1]);
System.out.print(words[0] + " ");
}
}
You can refer to the following code.
class ReverseString {
public static void main(String args[]) {
String myString = "The dog is chasing";
reverse(myString);
}
public static String reverse(String myString) {
int space = myString.indexOf(" ");
if (space != -1) {
reverse(myString.substring(space + 1, myString.length()));
}
if (space == -1) {
System.out.println(myString.substring(0, myString.length()));
} else {
System.out.println(myString.substring(0, space));
}
return myString;
}
}

How to reverse words in string in java without using split and stringtokenizer [closed]

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();
}

Categories

Resources