Is there a way to replace just one instance of a character in a string?

Tags: java
By : Henry
Source: Stackoverflow.com
Question!

I'm trying to replace the second "0" in 0003 while coding in Java. What method do I use in order to do this?

What about if I want to replace the second "4" in 3424? Is it the same method?

Thank you

By : Henry


Answers

This uses regex to find and replace the second instance of a given string:

public static String replaceSecondInstance(String input, String find, String replace) {
    find = Pattern.quote(find);
    replace = Matcher.quoteReplacement(replace);
    return input.replaceFirst("(" + find + ".*?)" + find, "$1" + replace);
}

public static void main(String[] args) {
    System.out.println(replaceSecondInstance("0003", "0", "x"));
    System.out.println(replaceSecondInstance("3424", "4", "y"));
}

Output:

0x03
342y
By : shmosel


There is a way to make CMake only include one -fopenmp. CMAKE_CXX_FLAGS is a string that you can search for substrings. You can conditionally add -fopenmp based upon whether you find it already in CMAKE_CXX_FLAGS. Assuming that you were careful not to already add it twice, then you can use the following check to see if you need to add it.

# find "-fopenmp"
string(FIND ${CMAKE_CXX_FLAGS} "-fopenmp" FLAG_INDEX)
# check if we found it
if (FLAG_INDEX GREATER 0)
   message(STATUS "WE'VE GOT AT LEAST ONE!")
else()
   message(STATUS "WE'VE GOT NONE; ADD IT!")
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")
endif()

Just to be safe you could remove all instances of -fopenmp and then add it back in.

# remove all occurrences of "-fopenmp"
string(REPLACE "-fopenmp" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})


You need a logical condition in the while. Perhaps

program.toUpperCase().equals("Y")
By : nicomp


This video can help you solving your question :)
By: admin