How to convert part of a string between two indexes to uppercase in Swift

1 Answer

0 votes
import Foundation

func convertPartToUppercase(str: String, startIndex: Int, endIndex: Int) -> String {
    // Check for valid indices 
    guard startIndex >= 0 && startIndex < str.count && endIndex >= startIndex && endIndex < str.count else {
        return str // Or throw an error if you prefer
    }

    // Use String.Index for correct indexing
    let start = str.index(str.startIndex, offsetBy: startIndex)
    let end = str.index(str.startIndex, offsetBy: endIndex + 1) // +1 for inclusive end index

    let range = start..<end
    let substring = str[range]

    let uppercaseSubstring = substring.uppercased()

    // Return the string with the replacement
    return str.replacingCharacters(in: range, with: uppercaseSubstring)
}

var s = "swift programming"

s = convertPartToUppercase(str: s, startIndex: 2, endIndex: 4)
print(s) 

s = convertPartToUppercase(str: s, startIndex: 13, endIndex: 14)
print(s) 



/*
run:

swIFT programming
swIFT programMIng

*/

 



answered Jan 30, 2025 by avibootz
...