Replacement of String in C# - string

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

Related

Is there a way to replace characters in a string from index 0 to index -4 (i.e. all but last 4 characters) with a '#'

For example, If my string was 'HelloWorld'
I want the output to be ######orld
My Code:
myString = 'ThisIsAString'
hashedString = string.replace(string[:-4], '#')
print(hashedString)
Output >> #ring
I expected the output to have just one # symbol since it is replacing argument 1 with argument 2.
Can anyone help me with this?
You could multiply # by the word length - 4 and then use the string slicing.
myString = 'HelloWorld'
print('#' * (len(myString) - 4) + myString[-4:])
myString = 'ThisIsAString'
print('#' * (len(myString) - 4) + myString[-4:])
string.replace(old, new) replaces all instances of old with new. So the code you provided is actually replacing the entire beginning of the string with a single pound sign.
You will also notice that input like abcdabcd will give the output ##, since you are replacing all 'abcd' substrings.
Using replace, you could do
hashes = '#' * len(string[:-4])
hashedString = string.replace(string[:-4], hashes, 1)
Note the string multiplication to get the right number of pound symbols, and the 1 passed to replace, which tells it only to replace the first case it finds.
A better method would be to not use replace at all:
hashes = '#' * (len(string) - 4)
leftover = string[-4:]
hashedString = hashes + leftover
This time we do the same work with getting the pound sign string, but instead of replacing we just take the last 4 characters and add them after the pound signs.

How to separate a string by Capital Letter?

I currently have to a code in ABAP which contains a String that has multiple words that start with Capital letters/Uppercase and there is no space in-between.
I have to separate it into an internal table like this:
INPUT :
NameAgeAddress
OUTPUT :
Name
Age
Address
Here is the shortest code I could find, which uses a regular expression combined with SPLIT:
SPLIT replace( val = 'NameAgeAddress' regex = `(?!^.)\u` with = ` $0` occ = 0 )
AT ` `
INTO TABLE itab.
So, replace converts 'NameAgeAddress' into 'Name Age Address' and SPLIT puts the 3 words into an internal table.
Details:
(?!^.) to say the next character to find (\u) should not be the first character
\u being any upper case letter
$0 to replace the found string ($0) by itself preceded with a space character
occ = 0 to replace all occurrences
Unfortunately, the SPLIT statement in ABAP does not allow a regex as separator expression. Therefore, we have to use progressive matching, which is a bit awkward in ABAP:
report zz_test_split_capital.
parameters: p_input type string default 'NameAgeAddress' lower case.
data: output type stringtab,
off type i,
moff type i,
mlen type i.
while off < strlen( p_input ).
find regex '[A-Z][^A-Z]*'
in section offset off of p_input
match offset moff match length mlen.
if sy-subrc eq 0.
append substring( val = p_input off = moff len = mlen ) to output.
off = moff + mlen.
else.
exit.
endif.
endwhile.
cl_demo_output=>display_data( output ).
Just for comparison, the following statement would do the job in Perl:
my $input = "NameAgeAddress";
my #output = split /(?=[A-Z])/, $input;
# gives #output = ('Name','Age','Address')
It is easy with using regular expressions. The solution could look like this.
REPORT ZZZ.
DATA: g_string TYPE string VALUE `NameAgeAddress`.
DATA(gcl_regex) = NEW cl_abap_regex( pattern = `[A-Z]{1}[a-z]+` ).
DATA(gcl_matcher) = gcl_regex->create_matcher( text = g_string ).
WHILE gcl_matcher->find_next( ).
DATA(g_match_result) = gcl_matcher->get_match( ).
WRITE / g_string+g_match_result-offset(g_match_result-length).
ENDWHILE.
For when regular expressions are just overkill and plain old ABAP will do:
DATA(str) = 'NameAgeAddress'.
IF str CA sy-abcde.
DATA(off) = 0.
DO.
data(tailstart) = off + 1.
IF str+tailstart CA sy-abcde.
DATA(len) = sy-fdpos + 1.
WRITE: / str+off(len).
add len to off.
ELSE.
EXIT.
ENDIF.
ENDDO.
write / str+off.
ENDIF.
If you do not want to use or cannot use Regex, here another solution:
DATA: lf_input TYPE string VALUE 'NameAgeAddress',
lf_offset TYPE i,
lf_current_letter TYPE char1,
lf_letter_in_capital TYPE char1,
lf_word TYPE string,
lt_word LIKE TABLE OF lf_word.
DO strlen( lf_input ) TIMES.
lf_offset = sy-index - 1.
lf_current_letter = lf_input+lf_offset(1).
lf_letter_in_capital = to_upper( lf_current_letter ).
IF lf_current_letter = lf_letter_in_capital.
APPEND INITIAL LINE TO lt_word ASSIGNING FIELD-SYMBOL(<ls_word>).
ENDIF.
IF <ls_word> IS ASSIGNED. "if input string does not start with capital letter
<ls_word> = <ls_word> && lf_current_letter.
ENDIF.
ENDDO.

LUA: Find and return string in double quotes

I try to find a string in a HTML-Body, the string looks like var version="1,1,0,0"; and i only want to extract the content between the double quotes. I have tried it with
local version = string.match(response.body, ".version.")
return version
You may use a var%s+version="([^"]+) pattern with string.match that will only output the captured text (i.e. the one matched with ([^"]+)) (see this Lua patterns tutorial):
s = [[var version="1,1,0,0";]]
res = string.match(s, [[var%s+version="([^"]+)]])
print(res)
See the Lua demo.
Details:
var - a literal var text
%s+ - 1+ whitespaces
version=" - literal version=" text
([^"]+) - a capturing group matching 1+ chars other than ".
If you want to specify that there can only be digits and commas inside version="...", use var%s+version="([%d,]+) pattern (see demo) where [%d,]+ matches 1+ digits or commas.
--> parsing first single quoted string only.
str1 = [[var version='1,1,0,0';]]
res1 = string.match(str1, "%b''")
res1 = string.gsub(res1, "'", '')
print(res1)
--> parsing first double quoted string only.
str2 = [[var version="1,1,0,0";]]
res2 = string.match(str2, '%b""')
res2 = string.gsub(res2, '"', "")
print(res2)
--> parsing all single quoted strings.
line1 = "major_ver='1', minor_ver='1.1'"
for chunk in string.gmatch(line1, "'(.-)'") do print(chunk) end
--> parsing all double quoted strings.
line2 = 'major_ver="2", minor_ver="2.2"'
for chunk in string.gmatch(line2, '"(.-)"') do print(chunk) end
line3 = [[major_ver="3", minor_ver="3.3"]]
for chunk in string.gmatch(line3, [["(.-)"]]) do print(chunk) end
Click on Lua demo for live result.

How to force text to be Upper case except selective strings c#

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
);

Evaluate equation but ignore order of mathematical operations and parentheses

I'm trying to write a function that ignores the order of mathematical operations and parentheses. The function just evaluates operators from left to right. (for +-*/^)
Example 1: 5 - 3 * 8^2 returns 256.
Example 2: 4 / 2 - 1^2 + (5*3) returns 18.
Here's what I did:
function out = calc(num)
[curNum, num] = strtok(num, '+-*/^');
out = str2num(curNum);
while ~isempty(num)
sign = num(1);
[curNum, num] = strtok(num, '+-*/^');
switch sign
case '+'
out = out + str2num(curNum);
case'-'
out = out - str2num(curNum);
case '*'
out = out.*str2num(curNum);
case '/'
out = out./str2num(curNum);
case '^'
out = out.^str2num(curNum);
end
end
end
My function doesn't ignore the left to right rule. How do I correct for this?
Your first example fails because you are splitting the string with the +-*/ delimiters, and you omitted the ^. You should change this to +-*/^ in lines 2 and 6.
Your second example fails because you aren't telling your program how to ignore the ( and ) characters. You should strip them before you enter the switch statement.
curNum = strrep(curNum,'(','')
curNum = strrep(curNum,')','')
switch sign
...
This is a way without any switch statements.
str = '4 / 2 - 1^2 + (5*3)'
%// get rid of spaces and brackets
str(regexp(str,'[ ()]')) = []
%// get numbers
[numbers, operators] = regexp(str, '\d+', 'match','split')
%// get number of numbers
n = numel(numbers);
%// reorder string with numbers closing brackets and operators
newStr = [numbers; repmat({')'},1,n); operators(2:end)];
%// add opening brackets at the beginning
newStr = [repmat('(',1,n) newStr{:}]
%// evaluate
result = eval(newStr)
str =
4/2-1^2+5*3
newStr =
((((((4)/2)-1)^2)+5)*3)
result =
18

Resources