C#:
string mystring = "Hello World. & my name is < bob >. Thank You."
Console.Writeline(mystring.ToUpper())
I am trying to get all the text to be uppercase except--
& < >
Because these are my encoding and the encoding wont work unless the text is lower case.
You may split the string with a space, turn all the items not starting with & to upper and just keep the rest as is, and then join back into a string:
string mystring = "Hello World. & my name is < bob >. Thank You.";
string result = string.Join(" ", mystring.Split(' ').Select(m => m.StartsWith("&") ? m : m.ToUpper()));
Another approach is to use a regex to match &, 1+ word chars and then a ;, and match and capture other 1+ word char chunks and only turn to upper case the contents in Group 1:
var result = System.Text.RegularExpressions.Regex.Replace(mystring,
#"&\w+;|(\w+)", m =>
m.Groups[1].Success ? m.Groups[1].Value.ToUpper() :
m.Value
);
I have a string "productname-producttype-front-view.png". I need to show it like "PRODUCTNAME-PRODUCTTYPE front view".
I have gone upto this much
string y = x.Replace(".png", " ").ToUpper();
Now , I am stuck...Please help. Thanks in advance
You may use the following regex-based approach:
var line = "productname-producttype-front-view.png";
var pattern = #"^(.*)-([^-]+-[^-]+)\.[^-.]+$";
var m = Regex.Match(line, pattern);
var result = string.Format("{0} {1}", m.Groups[1].Value.ToUpper(),
m.Groups[2].Value.Replace("-", " "));
Console.WriteLine(result);
See the C# demo
What it does:
Parses the string into the initial part and all that goes after the last but 1 hyphen, only capturing the initial part and the 2 subparts between - (not capturing the extension that will be dropped)
The intial part (Group 1) is just uppercased, while the trailing part gets all - turned into spaces.
Pattern explanation:
^ - string start
(.*) - Group 1 capturing any 0+ characters other than a newline as possible (but yielding a part of a string that matches the next subpatterns)
- - a hyphen
([^-]+-[^-]+) - Group 2 capturing 1+ chars other than -, then -, and again 1+ chars other than -
\.[^-.]+ - a dot followed with 1+ chars other than . and -
$ - end of string.
You could use Path.GetFileNameWithoutExtension and String.Split to extract the tokens:
string fileName = "productname-producttype-front-view.png";
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName);
string[] tokens = fileNameWithoutExtension.Split('-');
Now it's easy to get the desired result with the help of LINQ and String.Join:
var newTokens = tokens.Select((s, index) => index >= 2 ? s : s.ToUpper());
string result = String.Join(" ", newTokens); // puts a space between each token
I want to write an algorithm that removes every word started by an uppercase character in a string.
For example:
Original string: "Today is Friday the 29Th."
Desired result: "is the 29Th."
I wrote this algorithm, but it is not complete:
def removeUpperCaseChars(str: String) = {
for (i <- 0 to str.length - 1) {
if (str.charAt(i).isUpper) {
var j = i
var cont = i
while (str.charAt(j) != " ") {
cont += 1
}
val subStr = str.substring(0, i) + str.substring(cont, str.length - 1)
println(subStr)
}
}
}
It (supposedly) removes every word with uppercase characters instead of removing only the words that start with uppercase characters. And worse than that, Scala doesn't give any result.
Can anyone help me with this problem?
With some assumptions, like words are always split with a space you can implement it like this:
scala> "Today is Friday the 29Th.".split("\\s+").filterNot(_.head.isUpper).mkString(" ")
res2: String = is the 29Th.
We don't really want to write algorithms in the way you did in scala. This is reather a way you would do this in C.
How about string.replaceAll("""\b[A-Z]\w+""", "")?
How do I trim the starting and ending character of a string in Scala
For inputs such as ",hello" or "hello,", I need the output as "hello".
Is there is any built-in method to do this in Scala?
Try
val str = " foo "
str.trim
and have a look at the documentation. If you need to get rid of the , character, too, you could try something like:
str.stripPrefix(",").stripSuffix(",").trim
Another way to clean up the front-end of the string would be
val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)
which would also take care of strings like ",,, ,,hello"
And for good measure, here's a tiny function, which does it all in one sweep from left to right through the string:
def stripAll(s: String, bad: String): String = {
#scala.annotation.tailrec def start(n: Int): String =
if (n == s.length) ""
else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
else start(1 + n)
#scala.annotation.tailrec def end(a: Int, n: Int): String =
if (n <= a) s.substring(a, n)
else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
else end(a, n - 1)
start(0)
}
Use like
stripAll(stringToCleanUp, charactersToRemove)
e.g.,
stripAll(" , , , hello , ,,,, ", " ,") => "hello"
To trim the start and ending character in a string, use a mix of drop and dropRight:
scala> " hello,".drop(1).dropRight(1)
res4: String = hello
The drop call removes the first character, dropRight removes the last. Note that this isn't "smart" like trim is. If you don't have any extra character at the start of "hello,", you will trim it to "ello". If you need something more complicated, regex replacement is probably the answer.
If you want to trim only commas and might have more than one on either end, you could do this:
str.dropWhile(_ == ',').reverse.dropWhile(_ == ',').reverse
The use of reverse here is because there is no dropRightWhile.
If you're looking at a single possible comma, stripPrefix and stripSuffix are the way to go, as indicated by Dirk.
Given you only want to trim off invalid characters from the prefix and the suffix of a given string (not scan through the entire string), here's a tiny trimPrefixSuffixChars function to quickly perform the desired effect:
def trimPrefixSuffixChars(
string: String
, invalidCharsFunction: (Char) => Boolean = (c) => c == ' '
): String =
if (string.nonEmpty)
string
.dropWhile(char => invalidCharsFunction(char)) //trim prefix
.reverse
.dropWhile(char => invalidCharsFunction(char)) //trim suffix
.reverse
else
string
This function provides a default for the invalidCharsFunction defining only the space (" ") character as invalid. Here's what the conversion would look like for the following input strings:
trimPrefixSuffixChars(" Tx ") //returns "Tx"
trimPrefixSuffixChars(" . Tx . ") //returns ". Tx ."
trimPrefixSuffixChars(" T x ") //returns "T x"
trimPrefixSuffixChars(" . T x . ") //returns ". T x ."
If you have you would prefer to specify your own invalidCharsFunction function, then pass it in the call like so:
trimPrefixSuffixChars(",Tx. ", (c) => !c.isLetterOrDigit) //returns "Tx"
trimPrefixSuffixChars(" ! Tx # ", (c) => !c.isLetterOrDigit) //returns "Tx"
trimPrefixSuffixChars(",T x. ", (c) => !c.isLetterOrDigit) //returns "T x"
trimPrefixSuffixChars(" ! T x # ", (c) => !c.isLetterOrDigit) //returns "T x"
This attempts to simplify a number of the example solutions provided in other answers.
Someone requested a regex-version, which would be something like this:
val result = " , ,, hello, ,,".replaceAll("""[,\s]+(|.*[^,\s])[,\s]+""", "'$1'")
Result is: result: String = hello
The drawback with regexes (not just in this case, but always), is that it is quite hard to read for someone who is not already intimately familiar with the syntax. The code is nice and concise, though.
Another tailrec function:
def trim(s: String, char: Char): String = {
if (s.stripSuffix(char.toString).stripPrefix(char.toString) == s)
{
s
} else
{
trim(s.stripSuffix(char.toString).stripPrefix(char.toString), char)
}
}
scala> trim(",hello",',')
res12: String = hello
scala> trim(",hello,,,,",',')
res13: String = hello
Using VB6 without any additional references such as Regex, how can I convert a string so that all whitespace in a string is reduced to single spaces?
eg.
" A B C D E"
would be converted to
"A B C D E"
Function NormalizeSpaces(s As String) As String
Do While InStr(s, String(2, " ")) > 0
s = replace(s, String(2, " "), " ")
Loop
NormalizeSpaces = s
End Function
(derived from: http://www.techrepublic.com/article/normalizing-spaces-in-vb6-strings/5890164)