How can I set a specific positon in a String in Java? - java

I have a String with name str.
str = "hi john";
Now I want to set j char to g. How can I do that?

You can't modify a String directly, but you can either use a StringBuilder:
str = "hi john";
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(3,'g');
str = sb.toString();
.. or convert it to a char[] and back
str = "hi john";
char[] chars = str.toCharArray();
chars[3] = 'g';
str = new String(chars);

Two ways :
a. This will replace all occurances of 'j' with 'g'.
String str1 = "hi john";
System.out.println(str1); // prints - hi john
String str2 = str1.replace('j', 'g');
System.out.println(str2); // prints - hi gohn
b. If you wish to change the 'j' character only at one location in the string, you may want to do like this.
String str4 = replaceCharAt("hi john", 3,'g');
public static String replaceCharAt(String str1, int pos, char c) {
StringBuffer buf = new StringBuffer(str1);
buf.setCharAt(pos,c);
return buf.toString( );
}
// Here : pos = 3, char = 'g' and str1 = "hi john"

str = str.replace('j', 'g'); should do it for you.

str.replace('j','g');
as this java api shows
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace(char, char)

you can do like this
String str ="hi john"
syso(str.replace('j','g'));
Output will be hi gohn

You can use the substring. Look at :http://download.oracle.com/javase/tutorial/java/data/manipstrings.html

You can use something like this:
public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();
// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();
// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}
// Create string
sb.append(_text.substring(startPos,_text.length()));
return sb.toString();
}
public static int indexOf(String sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}

String s;
int i = str.indexOf('j');
s = str.subString(0, i) + 'g' + str.subString(i + 1, str.length() - 1);

Related

How do you replace all strings that are not between two characters?

Example (replacing 'text' with '...'):
Before:
text(text)text
After:
...(text)...
In this case it is easier to find what you want to keep, and replace the rest.
E.g. like this:
static String abbreviate(String input, String openTag, String closeTag) {
String regex = Pattern.quote(openTag) + ".*?" + Pattern.quote(closeTag);
StringBuilder buf = new StringBuilder();
int start = 0;
for (Matcher m = Pattern.compile(regex).matcher(input); m.find(); start = m.end()) {
if (start < m.start())
buf.append("...");
buf.append(m.group());
}
if (start < input.length())
buf.append("...");
return buf.toString();
}
Test
System.out.println(abbreviate("text(text)text(text)text", "(", ")"));
System.out.println(abbreviate("text$text$text$text$text$text", "$", "$"));
System.out.println(abbreviate("text(text)text", ")", "("));
Output
...(text)...(text)...
...$text$...$text$...
...
You need to iterate over the characters and only append those that are between the two specified characters. This can be done as follows:
private String splitStr(String str, char first, char second) {
StringBuilder sb = new StringBuilder();
if(str.isEmpty() || str.indexOf(first) < 0 || str.indexOf(second) < 0)
return sb.toString();
char[] chars = str.toCharArray();
boolean append = false;
for(char c : chars) {
if(c == first) {
sb.append(c);
append = true;
}else if(c == second) {
sb.append(c);
append = false;
}else if(append)
sb.append(c);
}
return sb.toString();
}
Some sample cases are:
"text(text)text(text)text(text)text" => "(text)(text)(text)"
"text(text)text" => "(text)"
String s = "text(text)text";
String newString = s.replace("text", "...");
System.out.println(newString); //returns ...(...)...
Note that "(text)" still contains "text", the braces around it will not stop it from being replaced.
You need to assign the result to a new String to use it. Strings are immutable

Replace fixed number of symbols in String

I have this number: 4200000000000000
I would like to leave only the first 4 digits and last 3 digits:
42000......000
Everything else should be replaced by dots. How I can implement this with some smart algorithm?
Why not use a StringBuilder and the substring method:
public static String foo(long num) {
String numToString = String.valueOf(num);
return new StringBuilder()
.append(numToString.substring(0 , 4))
.append("....")
.append(numToString.substring(numToString.length()-3, numToString.length()))
.toString();
}
When inputted 4200000000000000 it outputs:
4200....000
Or if the input is already a String:
public static String foo(String str) {
return new StringBuilder()
.append(str.substring(0 , 4))
.append("....")
.append(str.substring(str.length()-3, str.length()))
.toString();
}
Parse your number into a string and try this:
int last = 3;
int first = 4;
String number = '4200000000000000';
String start = number.substring(0,first-1);
String end = number.substring(number.length()-last,number.length()-1);
String dots = '';
for(int i = 0; i<number.length()-last-first;i++){
dots = dots + '.';
}
String result = start + dots + end;
You can use something like this,
public class Main {
public static void main(String[] args) {
System.out.println(convert("4200000000000000", 4, 3));
}
static String convert(String number, int firstDigits, int lastDigits) {
String first = number.substring(0, firstDigits);
String middle = number.substring(firstDigits, number.length() - lastDigits).replaceAll("0", ".");
String last = number.substring(number.length() - lastDigits, number.length());
return first + middle + last;
}
}
You could convert it to a char array, alter it, then convert it back into a string
char[] charArray = originalNumber.toCharArray();
for (int i; i < charArray.length; i++) {
if (i <= 4 || i >= charArray.length - 3) {
charArray[i] = ".";
}
}
String outputString = new String(charArray);
This will replace all chars from the 4th char up to the 4th from the end with '.':
String start = "4200000000000000";
System.out.println(start);
String target = start;
if (start.length() > 7) {
target = new StringBuilder()
.append(start.substring(0, 4))
.append(new String(new char[start.length() - 7]).replaceAll(".", "."))
.append(start.substring(start.length() - 3))
.toString();
}
System.out.println(target);
will print
4200000000000000
4200.........000
Using substring method of the String class :
String str = "4200000000000000";
String res = str.substring(0,4)+ str.substring(4,str.length()-3).replaceAll(".", ".") + str.substring(str.length()-3);
If you are using Apache commons library, you can use repeat method to create masking string of specified length and the overlay method of StringUtils class to overlay part of the String :
String str = "4200000000000000";
String mask= StringUtils.repeat('.', str.length()-7);
String res = StringUtils.overlay(str, mask, 4, str.length()-3);

How to check if character at current index in for loop is a specific character (e.g. the letter A, the number 2, etc)?

I'm building a simple program in Java that finds letters in strings and replaces them with a number, but I'm having trouble finding a method that will allow me to check for the exact specific character. There are plenty for digits and letters in general.
As my for loop stands now, it just replaces the letter everywhere, irregardless of whether it is within the range specified by start and end.
Any help would be appreciated.
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
for (int i = start; i < end; i++) {
if (Character.isLetter(str.charAt(i)) {
str = str.replaceAll("A", "9");
return str;
Expected Output:
A.A.9.9.9.A.A.A
Actual Output:
9.9.9.9.9.9.9.9
In your code, you have
str = str.replaceAll("A", "9");
This will replace all the occurrences of A to 9
Instead of your approach, you should
1.Convert the string to a char array
char[] charArray = str.toCharArray();
2.Then replace each occurrence of character with a number
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
3. Convert it back to string using
str = String.valueOf(charArray);
Modified Code:
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
//Converting String to char array
char[] charArray = str.toCharArray();
for (int i = start; i < end; i++) {
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
}
//Converting Back to String
str = String.valueOf(charArray);
System.out.println(charArray);
System.out.println(str);
Compare for character equality and then use string builder to replace the specified character
//Use of StringBuffer preferred over String as String are immutable
StringBuilder sb = new StringBuilder(str);
// -1 to start as index start from 0
for (int i = start-1; i < end; i++) {
char currentChar = currentString.charAt(i);
if (currentChar == "A") {
sb.setCharAt(i, '9');
}
}
return sb.toString();
I'd do it that way. Cut out the string to isolate the part you want to act on, do your replace ans stitch it all back together :
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String beginning = str.substring(0, startIndex);
String middle = str.substring(startIndex, endIndex);
String end = str.substring(endIndex);
middle = middle.replaceAll("A", "9");
String result = beginning + middle + end;
System.out.println(result);
Prints out :
A.A.9.9.9.A.A.A
EDIT:
As suggested in the comments, you could do it in one line
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String result =
str.substring(0, startIndex) +
str.substring(startIndex, endIndex).replaceAll("A", "9") +
str.substring(endIndex);
Here is an example using substrings to let you choose what portion of the string you want to test
int start = 3;
int end = 9;
String str = "A.A.A.A.A.A.A.A";
String startStr = str.substring(0,start);
String endStr = str.substring(end);
String newStr="";
char temp=' ';
for (int i = start; i < end; i++) {
temp = str.charAt(i);
if (temp=='A')
newStr+="9";
else
newStr += temp;
}
return(startStr + newStr + endStr);
You are replacing all the match found in the string and not specifying the index that needs to be replaced.
Use the StringBuffer replace method like below:
public static void main(String[] args) {
String str = "AAAAAAAA";
int start = 3;
int end = 9;
str = replaceBetweenIndexes(str, start, end, "9"); // AAA999AA
str = replaceBetweenIndexes("ABCD6EFG", start, end, "3"); // ABC363FG
}
public static String replaceBetweenIndexes(String str, int start, int end, String replaceWith) {
StringBuffer strBuf = new StringBuffer(str);
for (int i = start; i < end; i++) {
if (Character.isLetter(strBuf.charAt(i)) {
strBuf.replace(i, i+1, replaceWith);
}
}
return strBuf.toString();
}

How to switch two characters in a string?

Given a string as input, return the string with its last 2 chars swapped. And, if the string has less than 2 chars, do nothing and return the input string.
Here is the code I wrote so far:
public class SwapLastChars {
static String testcase1 = "Hello";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
if (length == 1)
return str1;
for (int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
Problem is in my test cases,any help?
Testcase Pass/Fail Parameters Actual Output Expected Output
1 pass 'aabbccdd' aabbccdd aabbccdd
2 fail 'A' null A
3 pass 'hello' helol helol
If you pass "A" you'll get StringIndexOutOfBoundsException rather than null. Unless you suppress it in a catch clause and return null.
Quick fix. Move the length check to start of the method. That should solve your issue.
public class SwapLastChars {
static String testcase1 = "A";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
if(str1 == null || str1.length() < 2) { //Move here
return str1;
}
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
for(int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
You should check for length at the very beginning of your function.
public String swap(String str1){
String str="";
int length=str1.length();
if (length <=2)
return str1;
char last=str1.charAt(length-1);
char l=str1.charAt(length-2);
for(int i=0;i<str1.length()-2;i++)
{
str=str+str1.charAt(i);
}
str=str+last+l;
return str;
}
I know this has already been answered, but I feel OPs swap method can be simplified by using a StringBuilder:
public static String swap(String word) {
//Answer by Syam
if (word == null || word.length() < 2) {
return word;
}
//Create new StringBuilder
StringBuilder s = new StringBuilder(word);
//Get second last char
char c = s.charAt(s.length() - 2);
//Replace second last char with last char
s.setCharAt(s.length() - 2, s.charAt(s.length() - 1));
//replace last char with stored char
s.setCharAt(s.length() - 1, c);
return s.toString();
}
Run:
System.out.println(swap("aabbccdd"));
System.out.println(swap("A"));
System.out.println(swap("hello"));
Output:
aabbccdd
A
helol
And here is why

Write a method to replace all spaces in a string with '%20'?

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.
I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.
public String replace(String str){
String[] words = str.split(" ");
StringBuffer sentence = new StringBuffer();
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
return sentence.toString();
}
Question in the book says:
Note: if implementing in Java, please use a character array so that
you can perform this operation in place.
It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").
In this loop, the program adds %20 before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
That will produce incorrect results, for example for a b it will give %20a%20b.
There's a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really don't want to use .replaceAll, then write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
You can also do the following, which replaces any space
String s = "Hello this is a string!";
System.out.println(replaceSpace(s, "%20"));
public static String replaceSpace(String s, String replacement) {
String ret = s.replaceAll(" *", replacement);
return ret;
}
Gives
Hello%20this%20is%20a%20string!
One of the simplest way:
public void replaceAll( String str )
{
String temp = str.trim();
char[] arr = temp.toCharArray();
StringBuffer sb = new StringBuffer();
for( int i = 0; i < arr.length; i++ )
{
if( arr[i] == ' ' )
{
sb.append( "%20" );
}
else
{
sb.append( arr[i] );
}
}
}
private static String applyReplaceOperationWithCount(String str) {
if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
return str;
}
char[] strChar = str.toCharArray();
int count = 0; //count spaces in the string to recalculate the array length
for (char c : strChar) {
if (c == ' ') {
count++;
}
}
if (count == 0) { // if there are no spaces in the string, return it
return str;
}
int length = strChar.length;
char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
int index = 0;
for (char c : strChar) {
if (c != ' ') { // if char is not a space just push it in the next available location
newChar[index++] = c;
} else { // if char is a space just push %,2,0
newChar[index++] = '%';
newChar[index++] = '2';
newChar[index++] = '0';
}
}
return new String(newChar); // convert the new array into string
}
I am using matches and replaceAll it works well.
public class ReplaceSpaces {
public static void main(String[] args) {
String text = " Abcd olmp thv ";
if(text.matches(".*\\s+.*")){
System.out.println("Yes I see white space and I am replacing it");
String newText = text.replaceAll("\\s+", "%20");
System.out.println(newText);
}
else{
System.out.println("Nope I dont see white spaces");
}
}
}
Output
Yes I see white space and I am replacing it
%20Abcd%20olmp%20thv%20
public static String replaceSpaceInString(String string,String toreplace){
String replacedString = "";
if(string.isEmpty()) return string;
string = string.trim();
if(string.indexOf(" ") == -1)return string;
else{
replacedString = string.replaceAll("\\s+",toreplace);
}
return replacedString;
}

Categories