How to get part of string between something? [closed] - java

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 8 years ago.
Improve this question
I have the string aaabbbccc.What is the best way to get bbb part?
UPD:
How to get ccc from aaabbbcccdddfff?

s.substring(s.indexOf("b"), s.lastIndexOf("b")-1)

StringUtils.substringBetween("aaabbbccc", "aaa", "ccc")
using StringUtils.substringBetween(...) from here

In this specific case,
String bbbString = "aaabbbccc".substring(3,6);
In response to the bit you just added to your question, I would say use the following function
public String getRepetitiveSubstringOf(String string, char desiredCharacter)
{
String theSubstring = null;
char[] charArray = string.toCharArray(); //it is more efficient to use arrays
//get the beginning position
int beginPosition = string.indexOf(desiredCharacter);
//get the end position (the desired substring length might NOT be 3, but rather, in this case,
//where the character value changes)
int endPosition = beginPosition;
//looping until we have either found a different character, or until we have hit the end of the
//character array (at the end, we loop one more time so that we can hit a garbage value that
//tells us to stop)
while ((charArray[endPosition] == desiredCharacter) || (endPosition < charArray.length))
{
endPosition++;
}
//if we have hit the garbage value
if (endPosition == charArray.length)
{
//we substring all the way to the end
theSubstring = string.substring(beginPosition);
}
else
{
//now, we check to see if our desiredCharacter was found AT ALL in the string
if (desiredCharacter > -1)
{
theSubstring = string.substring(beginPosition, endPosition);
}
}
return theSubstring;
}
From there, you can check for a return value of null

Try StringUtils.subStringBetween
String value = "aaabbbccc";
StringUtils.substringBetween(value, "aaa", "ccc");

For the string that you have specified you can use the code:
String result=s.substring(s.indexOf('b'),s.lastIndexOf('b'));
where s is your string,
For a more general string:
String result =s.substring(first index,last index);
where first index and last index are range that you want to extract.
Example:
String S="rosemary";
String result=s.substring(4,s.length());
This will store "mary" in the result string.

You only need one line and one method call if you use regex to capture the target group:
String middle = str.replaceAll(".*aaa(.*)ccc.*", "$1");

The best way maybe regEx.You could use
String str = str.replaceAll(a

Related

How to write a for loop for encoding and decoding in java? the program only encode one letter when I enter a string. College level 1 lesson [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I should write a encoding and decoding program in a class and then use it in main. The program needs the position for each letter to increase by 2.
When I run the program, the problem is that when I enter a string (like cookie), only the last letter is encoding. Here is a Screenshot of program running.
What is the problem for my program.
Thanks.
The lesson is very basic tho and the assignment are forbid students import any other java method like base64.Only use the starter code.
The code I will put here as well
public class SimpleCipher {
/*
* comments here to overview the method
*/
public String encode(String text) {
String result = "";
char[] chars = text.toCharArray();
int length = chars.length;
for (char x: chars) {
x+=2;
result = Character.toString(x);
}
// ToDo
// convert text into char array
// reverse the array using provided method (see below)
// loop over array adding 2 to each element
// convert the char array back to a String named result
// return the resulting String.
return result;
}
The main problem is that you are overwriting your result in each iteration.
Instead you want to append the character to the result string.
You can simply do that with
result = result + Character.toString(x);
result += Character.toString(x); // shorter version
result += x; // java can append characters to strings without explicit conversion
According to the comment that is - even tho it is working - not the desired solution anyways. The task is to create a new character array and fill it.
Do that by creating a new array of the same length as the original, iterating over the indexes of your arrays ( for (int i=0; i<chars.length; i++) ) and for each index write the updated character into the new array. The string class has a constructor that accepts a char array.

valid word counter out of bounds error [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 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Looking for best way to do this program [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 8 years ago.
Improve this question
I have two .txt files, first one looks like this :
XXXXXXX
XX0X0XX
XX000XX
XXXX0XX
XXXXXXX
and second like this :
.1..
.111
...1
....
First file needs to be seen as a hole made out of zeros and second as a figure make out of ones. I need to write an algorithm that reads both files and checks if "figure" out of second txt file fits into "hole" out of first one. What do you think is the most efficient way to do that ?
I think the best way is to read both files into arrays and then make comparision between arrays, but this is just my first thoughts.
Also final file should look like this :
XXXXXXX
XX1X0XX
XX111XX
XXXX1XX
XXXXXXX
One way could be to:
Load the first file in one array
Iterate over the second file and compare what you have in the array with what you have read in the file.
You can read both files line by line. Pass nth line from both the files to the following method:
public static boolean isFit(String a, String b) {
return a.replace('X', '.').replace('0', '1').equals(b);
}
If it return false then it is a mis-match otherwise at the end you can say that it is a match.
Here's a small method I threw together that determines whether or not a particular line of the figure matches a particular line in the hole.
public static int figureLineFits(char[] figure, char[] hole){
// Since figure max length per line is 4 and hole is 5
// we have to try to match it on either one end or the other.
char[] hole1 = Arrays.copyOfRange(hole, 0, hole.length-1);
char[] hole2 = Arrays.copyOfRange(hole, 1, hole.length);
// We get rid of the extra holes in the hole array.
for (int i = 0; i < 4; i++){
if(figure[i] == '.'){
if(hole1[i] == '0') hole1[i] = 'X';
if(hole2[i] == '0') hole2[i] = 'X';
}
}
// Convert the arrays to Strings because I'm
// lazy to lookup equivalent array methods.
String compFigure = figure.toString();
String compHole1 = hole1.toString();
String compHole2 = hole2.toString();
// Replace the 0s with 1s and Xs with .s in the hole strings.
compHole1.replace('0', '1');
compHole1.replace('X', '.');
compHole2.replace('0', '1');
compHole2.replace('X', '.');
// Set up some comparison booleans.
boolean leftComparison = compFigure.equals(compHole1);
boolean rightComparison = compFigure.equals(compHole2);
// Do some boolean logic to determine how the figure matches the hole.
// Will return 3 if figure can be matched on both sides.
// Will return 1 if figure can be matched on left side.
// Will return 2 if figure can be matched on right side.
// Will return 0 if figure doesn't match on either side.
if(leftComparison && rightComparison) return 3;
if(leftComparison) return 1;
if(rightComparison) return 2;
return 0;
}
Then you read the first line of the figure and try to match it with the lines of the hole.
If you can match it (the figureLineFits function doesn't return 0) then you can try to match the second line of the figure to the next line of the hole.
If that comparison doesn't return 0 then you have to check if the match is adequate, e.g. if the first line returned 1 and the next one returned 2 then the figure doesn't match. If the first line returned 3 and the second line returned either 1 or 2 then the match is adequate since the "3" means that it matches on both sides.
If you see that the match is not adequate you have to then go back to the first line of the figure and continue to match it on the line after you matched the first figure line not the consecutive figure lines since the first figure line might also match the second hole line although the second figure line didn't match the second hole line.
Hopefully this will get your head going in the right direction.

How to insert the string before of '#' in the email address? [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'm getting email address like user.q#stackoverflow.com. I want to add string before '#' symbol of email address in java.
After added string in the email address : user.qzzz#stackoverflow.com. How to insert 'zzz' string before # symbol in java ?
String input = "zzz";
String email = "user.q#stackoverflow.com";
int at = email.indexOf('#');
String newEmail = email.substring(0, at) + input + email.substring(at);
This will find the index of the at-sign:
int index = emailString.indexOf("#");
This will give you the first part of the string, before the at-sign:
String firstPart = emailString.substring(0, index);
This will give you the end part, starting with the at-sign
String lastPart = emailString.substring(index);
Put the bits together with your new stuff to make the result.
This should work, though not super efficient:
String s = email.substring(0, email.indexOf("#")-1)+"ZZZ"+email.substring(email.indexOf(#));
Another solution is using the split method of strings to get both sides of the string.
String email = "user.q#stackoverflow.com";
String[] strList = email.split("#");
strList[0] += "zzz";
email = strList[0] + "#" + strList[1];
System.out.println(email);

In Java what's the best way to get the last 250 characters of a string? [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
In Java what's the best way to get the last 250 characters of a string?
The string maybe empty, less than and greater than 250 chars.
Thanks
I would use StringUtils.right from Commons Lang, examples:
StringUtils.right("abc", 0) = ""
StringUtils.right("abc", 2) = "bc"
StringUtils.right("abc", 4) = "abc"
The easiest would be like this :-
public class check2 {
public static void main(String main[])
{
String temp = "Your String Of Some Size";
if(temp.length()>=250)
{
System.out.println(temp.substring(temp.length()-250));
}
else
{
//Since Size is less than 250 ,i display the same string
System.out.println(temp);
}
}
}
I don't exactly understand what you what, but this can do it:
if(string.length() > 250) {
char[] lastCharacters = (string.subString(string.length-250)).toCharArray;
}
This is a more compact way to do it:
public String getLast250Char(String input) {
return (input != null && input.length() > 250) ? input.substring(-250) : input;
}
Doing like this, you'll get a null return value once your input string is null.
public class twofiftystring{
public static void main(String main[])
{
String somestring = "String of arbitrary size";
String res = temp.length()>=250 ? somestring.substring(temp.length()-250 : somestring;
}
}
This should help:
string.substring(Math.max(0, string.length() - 250));
The Math.max() should work by selecting the highest positive value between 2 numbers provided.
This method will return the last 250 characters in the string, and else just return the string.
You can modify it to return an exception if the string has to be 250 characters or longer.
public String getLast250Characters(String text)
{
return (text.length() <= 250) ? text : text.substring((text.length() - 250));
}

Categories

Resources