I have tried a code to replace only specific character. In the string there are three same characters, and I want to replace the second or third character only. For example:
String line = "this.a[i] = i";
In this string there are three 'i' characters. I want to replace the second or third character only. So, the string will be
String line = "this.a[i] = "newChar";
This is my code to read the string and replace it by another string:
String EQ_VAR;
EQ_VAR = getequals(line);
int length = EQ_VAR.length();
if(length == 1){
int gindex = EQ_VAR.indexOf(EQ_VAR);
StringBuilder nsb = new StringBuilder(line);
nsb.replace(gindex, gindex, "New String");
}
The method to get the character:
String getequals(String str){
int startIdx = str.indexOf("=");
int endIdx = str.indexOf(";");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
I just assume that using an index is the best option to replace a specific character. I have tried using String replace but then all 'i' characters are replaced and the result string look like this:
String line = "th'newChar's.a[newChar] = newChar";
Here's one way you could accomplish replacing all occurances except first few:
String str = "This is a text containing many i many iiii = i";
String replacement = "hua";
String toReplace = str.substring(str.indexOf("=")+1, str.length()).trim(); // Yup, gets stuff after "=".
int charsToNotReplace = 1; // Will ignore these number of chars counting from start of string
// First replace all the parts
str = str.replaceAll(toReplace, replacement);
// Then replace "charsToNotReplace" number of occurrences back with original chars.
for(int i = 0; i < charsToNotReplace; i++)
str = str.replaceFirst(replacement, toReplace);
// Just trim from "="
str = str.substring(0, str.indexOf("=")-1);
System.out.println(str);
Result: This huas a text contahuanhuang many hua many huahuahuahua;
You set set charsToNotReplace to however number of first number of chars you want to ignore. For example setting it to 2 will ignore replacing first two occurrences (well, technically).
Related
I am trying to eventually replace a sentence with another set of String. But I hit a roadblock while trying to replace a char in a String with another character of another String.
Here's what I have so far.
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
//swapping each char of 'sentence' with the chars in 'encode'
for (int i = 0; i < sentence.length(); i++) {
int indexForEncode = letters.indexOf(sentence.charAt(i));
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
}
System.out.println(sentence);
This way of replacing characters doesn't work. Can someone help me?
The reason
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
doesn't work is that Strings are immutable (i.e., they never change).
So, sentence.replace(...) doesn't actually change sentence; rather, it returns a new String. You would need to write sentence = sentence.replace(...) to capture that result back in sentence.
OK, Strings 101: class dismissed (;->).
Now with all that said, you really don't want want to keep reassigning your partially encoded sentence back to itself, because you will, almost certainly, find yourself re-encoding characters of sentence that you already encoded. Best to leave sentence in its original form while building up the encoded string one character at a time like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sentence.length(); i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
sb.append(indexForEncode != -1
? encode.charAt(indexForEncode)
: sentence.charAt(i)
);
}
sentence = sb.toString();
I would use a character array as follows. Make the changes to a character array and then use String.valueOf to get the new version of the string.
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
char[] chars = sentence.toCharArray();
for (int i = 0; i < chars.length; i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
// if index is < 0, use original character, otherwise, encode.
chars[i] = indexForEncode < 0 ? chars[i] : encode.charAt(indexForEncode);
}
System.out.println(String.valueOf(chars));
Prints
xahhi, tbga zi jaaz wiq!
You can use codePoints method to iterate over the characters of this string and replace them with characters from another string, if any.
Try it online!
public static void main(String[] args) {
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
String sentence = "hello, nice to meet you!";
String encoded = replaceCharacters(sentence, letters, encode);
String decoded = replaceCharacters(encoded, encode, letters);
System.out.println(encoded); // xahhi, tbga zi jaaz wiq!
System.out.println(decoded); // hello, nice to meet you!
}
public static String replaceCharacters(String text, String from, String to) {
// wrong cipher, return unencrypted string
if (from.length() != to.length()) return text;
// IntStream over the codepoints of this text string
return text.codePoints()
// Stream<Character>
.mapToObj(ch -> (char) ch)
// encrypt characters
.map(ch -> {
// index of this character
int i = from.indexOf(ch);
// if not present, then leave it as it is,
// otherwise replace this character
return i < 0 ? ch : to.charAt(i);
}) // Stream<String>
.map(String::valueOf)
// concatenate into a single string
.collect(Collectors.joining());
}
See also: Implementation of the Caesar cipher
String add_filter = address.split("\\,", 2)[0];
This removes the text after the first comma. I need to remove the text after the second comma without using the loop.
address.split("\\,")[2];
That splits the string around commas. THe 0th index is before the first comma, the 1st is after the 1st comma, the 2nd is after the 2nd comma, etc. Note that this code assumes there's at least 2 commas. If there aren't, you need to save the array returned by split() and check the length to make sure its 3 or higher. Otherwise there was no second comma.
try following code :
//Finding the Nth occurrence of a substring in a String
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
then you can remove string after this index position the same as following code :
String newStr = address.substring(0,ordinalIndexOf(address,",",2)- 1)
Try below code
String s = "Hello,world,good bye";
s = s.replaceFirst(",(.*?),.*", " $1");
System.out.println(s);
So i want to arrange the string = "Deepak Pundir" into an order such as "Dpeuenpdaikr" by taking the first character of first name followed by first character of last name, then the second character of the first name, then the second character of the last name, and so on.
Here is a code snippit that shows you a basic algorithm for doing what you want:
String[] components = name.split(" "); // get the first and last names
if(components.length < 2) return; // check for valid string
StringBuilder build = new StringBuilder();
for(int x = 0;x < components[0].length && x < components[1].length;x++)
build.append(components[0].charAt(x) + components[1].charAt(x));
String result = build.toString();
For C, this algorithm is very similiar. You just need to use strtok instead of split:
strtok: get tokens from a string
i'm new to Java . How can i obtain right values of each line (second value of the dash separated pair)
Autorul-Stefan
DenumireaCartii-Popovici
CuloareaCartii-Verde
GenulCartii-Religie
Limba-Rusa
SOLVED :
String line = "Autorul-Stefan";
String [] fields = line.split("-");
fields[0] == "Autorul"
fields[1] == "stefan"
String line = "Autorul-Stefan";
String [] fields = line.split("-");
// fields[0] == "Autorul"
// fields[1] == "stefan"
use String.split():
String right = str.split("-")[1];
where str contains your String object
String strings = "Autorul-Stefan";
String[] tempo;
tempo = strings.split("-");
System.out.println(tempo[1]);
You can use the split() function in Strings:
String rightValue = line.split("-")[1];
Where line is the each line of your text (like "Autorul-Stefan") and rightValue is the text to the right of the dash (like "Stefan").
You use [1] to get the second element of the split text (split separates the given String into an array using the given character (here "-") as a divider) So in this example, the first element of the array is the text to the left of the dash and the second element is the text to the right of the dash.
I have this String :
String myStr = "something.bad#foo.us"
I want to get just the "something.bad" from myStr ?
You just need to use substring having found the right index to chop at:
int index = myStr.indexOf('#');
// TODO: work out what to do if index == -1
String firstPart = myStr.substring(0, index);
EDIT: Fairly obviously, the above takes the substring before the first #. If you want the substring before the last # you would write:
int index = myStr.lastIndexOf('#');
// TODO: work out what to do if index == -1
String firstPart = myStr.substring(0, index);
You can use
String str = myStr.split("#")[0];
It will split the string in two parts and then you can get the first String element