This is probably something very simple, but is there a way to make a string shorter. Something like:
string = "1234567980987654321";
From this string above I want only the first 9 characters.
new_string = "123456789"
You can use functionality built into the String class.
string = "1234567980987654321"
new_string = string[0, 9] #=> "123456798"
To add on for Rails (since it was tagged for Rails too),
You can use String#first
string = "1234567980987654321"
string.first(9) #=> "123456798"
In Ruby or Rails, another way do achieve your result would be by using range:
string = "1234567980987654321"
new_string = string[0..8] #=> "123456798"
Related
Context -
I have few strings which have some special characters in them which are supposed to be replaced / deleted to get the desired output.
What we need to do? -
Like I mentioned above -
Delete the character # if any are present in the string.
Replace the character / with _
For Instance -
Example 1) -
Input String -
string = "noMad#/places/-/contents/imr/-/pops/-"
Desired result-
output_string = "noMad_places_-_contents_imr_-pops_-"
Example 2) -
Input String -
string = "cat#/places/-/chart/rules"
Desired result-
output_string = "cat_places_-_chart_rules"
How can we do this in Ruby? Any leads would be appreciated!
Use tr
string = 'cat#/places/-/chart/rules'
p string.delete('#').tr('/','_')
output
"cat_places_-_chart_rules"
You can use a String class method named gsub()
The basic syntax of gsub in Ruby:
str.gsub!(pattern, replacement)
Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put.
For example
string1 = "noMad#/places/-/contents/imr/-/pops/-"
puts string1.gsub("#","").gsub("/","_")
Output
noMad_places_-_contents_imr_-_pops_-
If I have a string like this.
local string = "D:/Test/Stuff/Server/resources/[Test]/SuperTest"
How would I remove everything after the word "server" so it will end up look like this
local string = "D:/Test/Stuff/Server"
use str instead of string to not shadow the real string library
local str = "D:/Test/Stuff/Server/resources/[Test]/SuperTest"
here a solution
str = str:match("(.*Server)")
or use do...end to avoid shadowing
do
local string = ("D:/Test/Stuff/Server/resources/[Test]/SuperTest"):match("(.*Server)")
end
I have a string like below :
"[a06aad57-5671-482e-dbdd81dc39b1] Parameters: {\"ToCountry\"=>\"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e32a7503f7342b7065d77174d\"}"
I would like to capture only value of 'Parameters:' as below and convert it to hash. Key/value can be any value in above raw string :
{"ToCountry"=>"US", "ToState"=>"AL",
"SmsMessageSid"=>"SMa1a9e32a7503f3767342b7065d77174d"}
You can do it through a few steps:
require 'json'
string = "[a06aad57-5671-482e-dbdd81dc39b1] Parameters: {\"ToCountry\"=>\"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e32a7503f7342b7065d77174d\"}"
prepared_string = string.match(/Parameters:(.*)/)[1].gsub("=>", ":")
json = JSON.parse(prepared_string)
#=> {"ToCountry"=>"US", "ToState"=>"AL", "SmsMessageSid"=>"SMa1a9e32a7503f7342b7065d77174d"}
Not via regex and not the best approach evaling a user input but this will do it:
eval str.split("Parameters: ")[1]
Is there a function to capitalize each word in a string or is this a manual process?
For e.g. "bob is tall"
And I would like "Bob Is Tall"
Surely there is something and none of the Swift IOS answers I have found seemed to cover this.
Are you looking for capitalizedString
Discussion
A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
and/or capitalizedStringWithLocale(_:)
Returns a capitalized representation of the receiver using the specified locale.
For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.
Swift 3:
var lowercased = "hello there"
var stringCapitalized = lowercased.capitalized
//prints: "Hello There"
Since iOS 9 a localised capitalization function is available as capitalised letters may differ in languages.
if #available(iOS 9.0, *) {
"istanbul".localizedCapitalizedString
// In Turkish: "İstanbul"
}
An example of the answer provided above.
var sentenceToCap = "this is a sentence."
println(sentenceToCap.capitalizedStringWithLocale(NSLocale.currentLocale()) )
End result is a string "This Is A Sentence"
For Swift 3 it has been changed to capitalized .
Discussion
This property performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the current locale.
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart(_:end:contentsEnd:for:)). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercased for an example.
There is a built in function for that
nameOfString.capitalizedString
This will capitalize every word of string. To capitalize only the first letter you can use:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
Older Thread
Here is what I came up with that seems to work but I am open to anything that is better.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
or if I want to use this as an extension of the string class.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Again, anything better is welcome.
Swift 5 version of Christopher Wade's answer
let str = "my string"
let result = str.capitalized(with: NSLocale.current)
print(result) // prints My String
In my code I have to match below 3 types of data
abcd:xyz:def
def:xyz
xyz:def
where "xyz" is the real data and other part are Junk data. Now, for first 2 types as below I can split with ':' and can get the array[1] position data ... which will give me the correct one.
abcd:xyz:def
def:xyz
I am not getting How can extract the 3rd case. Any idea? Please help.
Thanks,
Rahul
string case1 = "abcd:xyz:def";
string case2 = "def:xyz";
string case3 = "xyz:def";
string result1 = case1.Split(':')[1];
string result2 = case2.Split(':')[1];
string result3 = case3.Split(':')[0];
If I understand your question correctly.
Use array[0] instead of array[1] in the third case after splitting.