Add toSnakeCase method to StringUtils #1310
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Description: Add
toSnakeCase
Method toStringUtils
Summary
This PR introduces the
toSnakeCase(String str)
method to theStringUtils
class in Apache Commons Lang. This method converts camelCase or PascalCase strings to snake_case, enhancing the library’s support for string case transformations. The optimized implementation ensures accurate conversion, even when dealing with sequences of uppercase letters, and reduces unnecessary condition checks for improved readability and performance.Why This Change is Needed
String case transformations are widely used across applications, especially when adhering to naming conventions for different domains (e.g., snake_case for database fields, camelCase for variables in code). Currently,
StringUtils
lacks a direct method for converting camel case to snake case, which is essential in many applications. This enhancement provides a reliable and performant way to handle camelCase-to-snake_case transformations without requiring developers to implement custom solutions.Method Behavior
The
toSnakeCase
method:"camelCase"
,"CamelCase"
) to snake_case (e.g.,"camel_case"
)."JSONParser"
to"json_parser"
without unnecessary underscores.null
fornull
inputs and an empty string for empty inputs.Examples
Implementation Details and Optimizations
prevChar
variable to track the previous character, reducing redundant checks onstr.charAt(i - 1)
.Unit Tests
Unit tests have been added in
StringUtilsTest
to verify the correctness oftoSnakeCase
:null
, empty strings, single uppercase letters, and already snake case strings.Example Test Cases
Additional Notes
This optimized implementation is efficient with a time complexity of (O(n)) and minimal overhead. The added functionality aligns with Apache Commons Lang's design philosophy, providing a simple, well-tested solution for common string transformations.