locate specific char and replace it in Java - java

I am getting around a hundred url strings from my JSON. Example:
media.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_189765_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_162_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_532535677_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_1612452_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_10976562**_b.jpg**
As you see, the only common thing in these urls is the end "b.jpg"
How can I replace the character b with other character?
I have tried with this method:
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
Here is when I call it:
hs.thumbNailUrl = changeCharInPosition(65, 'l',hs.thumbNailUrl);
But the position of b always changes, so this method is inefficient.

If you are always only going to have one char of that value you can just use .replace() to replace that character.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace('b', 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
Now if you are trying to replace based off of the index of the character you could use StringBuilder and find the location of b by using substring and finding the location of b by subtracting the the number of chars after b from the total length.
public static void main(String args[]) {
StringBuilder x = new StringBuilder("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x.setCharAt(x.length() - 7, 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
EDIT
Third option:
Here we are replacing the char at the last index of 'b'.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace(x.charAt(x.lastIndexOf('b')), 'y');
System.out.println(x);
}
Now obviously you can loop through and use a new character for each string.

Change your call to changeCharInPosition from
hs.thumbNailUrl = changeCharInPosition(65, 'l', hs.thumbNailUrl);
to
hs.thumbNailUrl = changeCharInPosition(hs.thumbNailUrl.indexOf("b.jpg"),
'l', hs.thumbNailUrl);

You can use String.lastIndexOf(String) in order to find the last occurrence of one String inside another.
e.g.
private String replace(String url, String thumnailUri){
String toReplace = "**b.jpg**";
int lastBIndex = url.lastIndexOf(toReplace);
return url.substring(0, lastBIndex) + thumnailUri;
}
You could also use String.replace(String, String) e.g.
url.replace("**b.jpg**", hs.thumnailUri);

Related

Why to add a Empty String while adding an string with int?

In the below when I wasn't adding the ""(Empty String), the output was in int, which is pretty abnormal because adding a String with an int always gives a string. But as soon as I added the Empty String thing, the code seemed to work fine. In both the cases,I was adding a string from the string array that I created earlier in the code.
import java.io.*;
public class TooLong{
public static void main(String[] args) throws IOException{
InputStreamReader n = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(n);
byte i ;
i=Byte.parseByte(input.readLine());
String origWords[] = new String[i];
for (int j=0;j<i;j++) origWords[j]= input.readLine();
for (int j=0;j<i;j++){
int charLength = origWords[j].length();
if (charLength < 11) System.out.println(origWords[j]);
else System.out.println(origWords[j].charAt(0) +""+ (charLength-2) + origWords[j].charAt(charLength-1) );
}
}
}
I assume, you are trying to achieve “internationalization ⇒ i18n”
That is because String.charAt(int) returns char. Which will be treated as numerical when using +.
By using + with the empty String you force the compiler to convert everything to String
You can use String.substring(0,1) instead of the first charAt to force type String conversion
The charAt() method of String returns the char. char is one of the primitive data types. char is a textual primitive, however, it also can do arithmetic operations like numerical primitives. The codes below are examples for it:
`public static void main(String args[]){
String st = "i am a string";
char c = st.charAt(0);
System.out.println(c);
System.out.println(c+ st.charAt(2));
System.out.println(c+ "" + st.charAt(2));
}
`
The result of the above code will be:
i
202
ia
Hope this example makes it clear.

java find if the string contains 2 other strings

I have 2 strings "test" "bet" and another string a="tbtetse". I need to check if the "tbtetse" contains the other two strings.
I was thinking if I could find all the anagrams of string a and and then find the other two strings in those, but it doesn't work that way and also my anagram code is failing for a lengthy string.
Could you please help with any other ways to solve it?
Assuming you're trying to test whether the letters in a can be used to form an anagram of the test strings test and bet: I recommend making a dictionary (HashMap or whatever) of character counts from string a, indexed by character. Build a similar dictionary for the words you're testing. Then make sure that a has at least as many instances of each character from the test strings as they have.
Edit: Alcanzar suggests arrays of length 26 for holding the counts (one slot for each letter). Assuming you're dealing with only English letters, that is probably less of a hassle than dictionaries. If you don't know the number of allowed characters, the dictionary route is necessary.
Check below code, it may help you.
public class StringTest {
public static void main(String[] args) {
String str1 = "test";
String str2 = "bev";
String str3 = "tbtetse";
System.out.println(isStringPresent(str1, str2, str3));
}
private static boolean isStringPresent(String str1, String str2, String str3) {
if ((str1.length() + str2.length()) != str3.length()) {
return false;
} else {
String[] str1Arr = str1.split("");
String[] str2Arr = str2.split("");
for (String string : str1Arr) {
if (!str3.contains(string)) {
return false;
}
}
for (String string : str2Arr) {
if (!str3.contains(string)) {
return false;
}
}
}
return true;
}
}
basically you need to count characters in both sets and compare them
void fillInCharCounts(String word,int[] counts) {
for (int i = 0; i<word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
counts[index]++;
}
}
int[] counts1 = new int[26];
int[] counts2 = new int[26];
fillInCharCounts("test",counts1);
fillInCharCounts("bet",counts1);
fillInCharCounts("tbtese",counts2);
boolean failed = false;
for (int i = 0; i<counts1.length; i++) {
if (counts1[i] > counts2[i]) {
failed = true;
}
}
if (failed) {
whatever
} else {
something else
}
If you are generalizing it, don't forget to call .toLowerCase() on the word before sending it in (or fix the counting method).
Pseudo code:
Make a copy of string "tbtetse".
Loop through each character in "test".
Do a indexOf() search for the character in your copied string and remove it if found.
If not found, fail.
Do the same for the string "bet".
class WordLetter {
char letter;
int nth; // Occurrence of that letter
...
}
One now can use Sets
Set<WordLetter>
// "test" = { t0 e0 s0 t1 }
Then testing reduces to set operations. If both words need to be present, a union can be tested. If both words must be formed from separate letters, a set of the concatenation can be tested.

How can i use substring or other function to divide a string into words?

So I have this function:
public void actionPerformed(ActionEvent e)
{
String input = jt.toString();
}
And I want to use substring or any other function to divide the words in this sentence.
Like using substring from 0 until it finds a "space" and then it should stop and then start again until the end of the sentence.
What you need is to use the Split method for the String class.
String[] input = jt.toString().split("\\s+");
This method will give you an array where each cell of the array will contain a word.
jt stands for JText?
If yes, you should get the text from the component instead of converting the object to string using the following instruction: jt.getText()
string[] words = input.Split(' ')
You can also do it with stringbuilder if you care about saving memory.
public class splitword {
public static void main(String[] args) {
String input = "Hi! Can you please split me into pieces :0";
String[] toSplit = new StringBuilder(input).toString().split("[\\s\\p{P}&& [^']]+");
for (String x : toSplit) {
System.out.println(x);
}
}
}

Arrays.toString() prints String with [] and , ---any alternative?

while programming i accepted a string ...changed it to char array using
string.toCharArray()
...and had to change it back to string (because i am using recurion and have to pass the string as argument each time)..how to do this..???
i tried using array.toString()...but it passes gibberis..beginning with #....then i searched here and found out about Arrays.toString().....but learned that it does indeed convert it to string but adds [] and , ...i need the original string....how to go about this...heres part of the code..
public String replace(String str, char ch) {
if(count ==0){
Scanner sc2= new Scanner(System.in);
System.out.println("enter the character to be replaced with ");
c2 =sc2.next().charAt(0);
len=str.length();
}
arr=str.toCharArray();
if(arr[count]==ch){
arr[count]=c2;
}
count++;
str=Arrays.toString(arr); // Problem
if(count<len)
temp=replace(str,ch);
else
temp=str;
return temp;
}
Try this
String chString = new String(myCharArray);
If you want to convert a char[] to a String, then just use new String(array).
You can pass this array to String constructor:
String original = new String(arr);

Extract a substring up to 1000th comma

I have a string (comma seperated)
For example:
a,bgf,sad,asd,rfw,fd,se,sdf,sdf,...
What I need is to extract a substring up to the 1000th comma.
How to achieve this in Java?
An efficient way of doing this would be to use indexof(int ch, int fromIndex) intead of using split(String regex, int limit) or split(String regex) especially if the given string is long.
This could be done something like this
[pseudocode]
asciiCodeForComma = 0x2c
nextIndex=0
loop 1000 times
nextIndex= csv.indexof(asciiCodeForComma , nextIndex)
requiredSubString = csv.subString(0, nextIndex)
String csv = "some,large,string";
String[] parts = csv.split(",");
String thousandthElement = null; // the default value if there are less than 1000
if (parts.length > 999)
thousandthElement = parts[999];
You can use StringTokenizer with comma as separator, then loop nextToken() 1000 times.
I think he is asking for all 1000 element.. This should solve your problem. Understand and then copy-paste as this is ur homework :)
public static void main(String[] args) {
// TODO Auto-generated method stub
String samplecsv = "a,bgf,sad,asd,rfw,fd,se,sdf,sdf,";
String[] splitedText = samplecsv.split(",");
StringBuffer newtext = new StringBuffer();
for (int i = 0; i < 3; i++) {
newtext.append(splitedText[i]);
}
System.out.println(newtext);
}
So to solve this problem what you need to do is understand how to extract a string from a delimiter separated input stream. Then executing this for the case for N strings is trivial. The pseudocode for doing this for the individual record is below:
function parse(inputValue, delimiter)
{
return inputValue.split(delimiter)
}
Now to do that for the case where there are N inputValues is equally as trivial.
function parse(inputValues, delimiter)
{
foreach inputValue in inputValues
returnValue.append(parse(inputValue,delimiter)
return returnValue
}
There is actually built in functionality to do this by putting a second argument into split. If what you're really looking for is the whole string before the 1000th comma, you can still use this function but you will have to concatenate the first section of the array.
public static void main(String[] args){
String sample = "s,a,m,p,l,e";
String[] splitSample = sample.split(",",1000);
if (splitSample.length == 1000)
System.out.println(splitSample[1000]);
else
System.out.println("Your error string");
}

Categories

Resources