How to replace a string with star except first character in kotlin - string

I want to know how can I replace a given string with stars except first character of string in kotlin
For e.g i have string "Rizwan" , I want it to be R*****

You can do it with padEnd():
val name = "Rizwan"
val newName = name[0].toString().padEnd(name.length, '*')
Result:
"R*****"

Try replace center of String like Phone number. with ★:
phone.replaceRange(2 , phone.length-3 , "★".repeat(phone.length-5))
pay attention to 2 + 3 = 5 :D
Result:
"09★★★★★229"

Try replacing (?<=.). with *:
val input = "Rizwan"
val output = input.replace(Regex("(?<=.)."), "*")
println(output)
This prints:
R*****
The lookbehind (?<=.) in the regex pattern ensures that we only replace a character if at least one character precedes it. This spares the first character from being replaced.

I am not an expert in Kotlin so this may not be the best way to do it but it will work for sure.
var s = "Rizwan"
var l = s.length
val first = s[0]
s=""
while(l>1) {
s=s+"*"
l--
}
s=first+s
print(s)
Basic Algorithm..... using no library or functions

val name = "Rizwan"
val newName = name[0].toString().padEnd(name.length, '*')
Result:
"R*****"

Related

Kotlin Regex to Extract after and before a specific character

In Kotlin, i need to find the string value after and before of specific character,
For example,
Item1. myResultValue: someother string
So in the above, I need to get the value after ". " and before ":" SO my output should be "myResultValue". If it doesn't match it can return empty or null value.
Please help to write to Regex for this.
For your specific case you can use regex:
val text = "Item1. myResultValue: someother string"
val pattern = Pattern.compile(".*\\.(.*):.*")
val matcher = pattern.matcher(text)
if (matcher.matches()) {
println(matcher.group(1))
}
If you want to build something smarter that defines the start and end pattern you can do it like this:
val startSearch = "\\."
val endSearch = ":"
val text = "Item1. myResultValue: someother string"
val pattern = Pattern.compile(".*$startSearch(.*)$endSearch.*")
val matcher = pattern.matcher(text)
if (matcher.matches()) {
println(matcher.group(1))
}

Node split string by last space

var str="72 tocirah abba tesh sneab";
I currently have this string and want a new string that is called "72 tocirah abba tesh". What is the best way to do this in node/Javascript?
Another one-liner:
"72 tocirah abba tesh sneab".split(" ").slice(0, -1).join(" ")
Basically, you split the string using the space separator, slice the resulting array removing the last item, and join the array using the space separator.
You can use replace, like:
"72 tocirah abba tesh sneab".replace(/\s\w+$/, '')
(This replaces the last space and word with an empty string)
I would solve it like that:
let str = "72 tocirah abba tesh sneab"
Split by " ":
let list = str.split(" ") // [72,tocirah,abba,tesh,sneab]
Remove the last element using pop():
list.pop() // [72,tocirah,abba,tesh]
Then join it back together:
str = list.join(" ") // 72 tocirah abba tesh
Following is one of the ways to handle this.
use lastIndexOf function
const lastSpacePosition = str.lastIndexOf(" ");
// in case there is no space in the statement. take the whole string as result.
if(lastSpacePosition < 0) {
lastSpacePosition = str.length;
}
str.substr(0, lastSpacePosition);
There are other ways to handle this using regEx, split->join as well

Remove words of a string started by uppercase characters in Scala

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+""", "")?

Find substring of string w/o knowing the length of string

I have a string x: x = "{abc}{def}{ghi}"
And I need to print the string between second { and second }, in this case def. How can I do this without knowing the length of the string? For example, the string x could also be {abcde}{fghij}{klmno}"
This is where pattern matching is useful:
local x = "{abc}{def}{ghi}"
local result = x:match(".-{.-}.-{(.-)}")
print(result)
.- matches zero or more characters, non-greedy. The whole pattern .-{.-}.-{(.-)} captures what's between the second { and the second }.
Try also x:match(".-}{(.-)}"), which is simpler.
I would go about it in a different manner:
local i, x, result = 1, "{abc}{def}{ghi}"
for w in x:gmatch '{(.-)}' do
if i == 2 then
result = w
break
else
i = i + 1
end
end
print( result )

Deleting underscores at the end of string Matlab

I have a string array
Str_in = {'ab_cd_a9_b5__','ab_cd_r_','ef_g','3swe_4r_2345___','swe','eds______'};
how to delete the trailing underscores in the above string array. The length of each string is not constant and the n umber of underscores may vary. The expected output string is
Str_out = {'abcda9_b5','ab_cd_r','ef_g','3swe_4r_2345','swe','eds'};
Would any one help on this issue?
It's convenient to use regex to replace these characters. The pattern of trailing _ is (number of '_' is greater than or equals 1):
_+$
So the code is:
Str_in = {'ab_cd_a9_b5__','ab_cd_r_','ef_g','3swe_4r_2345___','swe','eds______'};
Str_out = cellfun(#(x) regexprep(x, '_+$', ''), Str_in, 'UniformOutput', false);
% or do as Shai mentioned,
Str_out = regexprep(Str_in, '_+$', '');
disp(Str_out);
Output:
'ab_cd_a9_b5' 'ab_cd_r' 'ef_g' '3swe_4r_2345' 'swe' 'eds'

Resources