I need to replace a string with a uppercase of the same word.So far i can search for sub-string from a text file which contains my string and replace a word like "apple" or "Apple" or "ApPle" to "APPLE". The problem exist when the string is "Is that pineapple Apple adamsApple applepie smell?", my search keyword exist between the other word so it cannot be found and converted.
MY final working code:
//Get the txt file from the directory and search for word
func fileRead(getPath string, searchkey string){
var count int
buf1,_:=ioutil.ReadFile(getPath);
var buf2= string(buf1)
var b string
tokens:=strings.Fields(buf2)
re := regexp.MustCompile("(?i)"+searchkey)//make searchkey case insensitive
for i:=0;i<len(tokens);i++{
if (strings.EqualFold(tokens[i],searchkey)){
tokens[i] = re.ReplaceAllString(tokens[i], strings.ToUpper(searchkey))
count++
}else{
tokens[i]=re.ReplaceAllLiteralString(tokens[i],strings.ToUpper(searchkey))
count++
}
}
for j:=0; j<len(tokens); j++{
b+= tokens[j]
b+=" "
}
c := []byte(b)
fmt.Println(count," ",getPath)
ioutil.WriteFile(getPath, c, 0644)//rights back to the file
}