Documentação Documentação de módulo


A documentação para este módulo pode ser editada em Módulo:String/doc.

Função length

{{#invoke:String|length|1=string}} ou {{#invoke:String|length|string}}

Recebe uma string como argumento e devolve o seu comprimento. Em particular, se a string fornecida é vazia, retorna 0.

  • {{#invoke:String|length|}} → 0
  • {{#invoke:String|length| }} → 1
  • {{#invoke:String|length|carro}} → 5
  • {{#invoke:String|length|carroça}} → 7
  • {{#invoke:String|length| 1234567}} → 8
  • {{#invoke:String|length| ab cde}} → 7
  • {{#invoke:String|length|borracheiro}} → 11
  • {{#invoke:String|length| café åäö}} → 9
  • {{#invoke:String|length|paralelepípedo}} → 14
Ver também
mw.ustring.len

Função substring

{{#invoke:String|substring|1=string|2=índice_inicial|3=índice_final}} ou
{{#invoke:String|substring|string|índice_inicial|índice_final}}

Recebe uma string e dois inteiros como argumentos e devolve uma substring da string de entrada. O primeiro inteiro é o índice no qual começa a substring e o segundo o índice no qual termina. Da esquerda para a direita, o primeiro caractere da string fornecida está na posição de índice 1; o segundo (se existir) na posição de índice 2; etc. E, da direita para a esquerda, o último caractere da string pode ser referenciado pelo índice -1; o penúltimo (se a string possuir mais do que um caractere) pelo índice -2; o ante-penúltimo, se existir, -3; etc. Por omissão, o índice inicial (parâmetro 2) tem valor 1 (primeiro caractere da string) e o índice final valor -1 (último caractere), de modo que, por omissão desses índices, é devolvida na saída a string de entrada.

  • {{#invoke:String|substring|}}
  • {{#invoke:String|substring| }}
  • {{#invoke:String|substring|carroça}} → carroça
  • {{#invoke:String|substring|carroça|1|5}} → carro
  • {{#invoke:String|substring|carroça||5}} → carro
  • {{#invoke:String|substring|carroça||}} → carroça
  • {{#invoke:String|substring|carroça|4|7}} → roça
  • {{#invoke:String|substring|carroça|4}} → roça
  • {{#invoke:String|substring|carroça|4|}} → roça
  • {{#invoke:String|substring|carroça|4|-1}} → roça
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma||1}} → O
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|1|1}} → O
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|3|6}} → rato
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|13|13}} → a
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|21|22}} → do
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|21|-13}} → do
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|-14|-13}} → do
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|31|34}} → Roma
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|31|-1}} → Roma
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|31|55}} → Roma
  • {{#invoke:String|substring|O rato roeu a roupa do rei de Roma|34|31}}
Ver também
mw.ustring.sub

Função charAt

{{#invoke:String|charAt|1=string|2=índice}} ou {{#invoke:String|charAt|string|índice}}

Recebe uma string e um inteiro (índice) e, na saída, retorna o caractere que ocupa a posição cujo índice foi fornecido. Um índice igual a 1 corresponde ao primeiro caractere; um índice igual a 2, ao segundo (se existir); um índice igual a 3, ao terceiro (se existir) etc. Um índice igual a -1 corresponde ao último caractere da string; um índice igual a -2, ao penúltimo; um índice igual a -3, ao ante-penúltimo; etc. Se o valor absoluto do índice excede o comprimento da string, é retornada uma mensagem de erro informando que o valor fornecido está fora do escopo.

  • {{#invoke:String|chartAt|}} → NULL
  • {{#invoke:String|charAt| }} → NULL
  • {{#invoke:String|chartAt|carroça}} → NULL
  • {{#invoke:String|charAt|carroça|}} → NULL
  • {{#invoke:String|charAt|carroça| }} → NULL
  • {{#invoke:String|charAt|carroça|0}} → NULL
  • {{#invoke:String|charAt|carroça|1}} → c
  • {{#invoke:String|charAt|carroça|2}} → a
  • {{#invoke:String|charAt|carroça|3}} → r
  • {{#invoke:String|charAt|carroça|5}} → o
  • {{#invoke:String|charAt|carroça|6}} → ç
  • {{#invoke:String|charAt|carroça|7}} → a
  • {{#invoke:String|charAt|carroça|-1}} → a
  • {{#invoke:String|charAt|carroça|-2}} → ç
  • {{#invoke:String|charAt|carroça|-3}} → o
  • {{#invoke:String|charAt|carroça|10}}O índice fornecido está fora do escopo.
  • {{#invoke:String|charAt|carroça|-10}}O índice fornecido está fora do escopo.
  • {{#invoke:String|charAt|0123456789ABCDEF|15}} → E
  • {{#invoke:String|charAt|0123456789ABCDEF|-1}} → F
  • {{#invoke:String|charAt|0123456789ABCDEF|-2}} → E
  • {{#invoke:String|charAt|0123456789ABCDEF|-3}} → D
  • {{#invoke:String|charAt|0123456789ABCDEF|18}}O índice fornecido está fora do escopo.
  • {{#invoke:String|charAt|0123456789ABCDEF|-18}}O índice fornecido está fora do escopo.

Função repete

{{#invoke:String|repete|1=string|2=n}} ou {{#invoke:String|repete|string|n}}string concatenada n vezes

  • {{#invoke:String|repete|carro}}O segundo parâmetro fornecido não é um inteiro positivo.
  • {{#invoke:String|repete|carro|}}O segundo parâmetro fornecido não é um inteiro positivo.
  • {{#invoke:String|repete|carro| }}O segundo parâmetro fornecido não é um inteiro positivo.
  • {{#invoke:String|repete|carro|1}} → carro
  • {{#invoke:String|repete|carro|8}} → carrocarrocarrocarrocarrocarrocarrocarro
  • {{#invoke:String|repete|carro|-5}}O segundo parâmetro fornecido não é um inteiro positivo.
  • {{#invoke:String|repete|<br>|3}}


  • {{#invoke:String|repete|Ελλάδα|10}} → ΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδαΕλλάδα
  • {{#invoke:String|repete|Češi|15}} → ČešiČešiČešiČešiČešiČešiČešiČešiČešiČešiČešiČešiČešiČešiČeši
Ver também
mw.ustring.rep e {{repeat}}

Função procura

{{#invoke:String|procura|1=texto|2=substring}} ou {{#invoke:String|procura|texto|substring}}

Retorna a posição da primeira ocorrência de substring em texto. Em particular, se substring não é passada ou não encontrada, o retorno é igual a -1.

  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|}} → 1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|O}} → 1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|rato}} → 3
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|rato|5}} → -1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|roupa}} → 15
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|roupa|10}} → 15
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|roupa|15}} → 15
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|roupa|20}} → -1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|rei}} → 24
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|rei|10}} → 24
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|rei|25}} → -1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|Roma}} → 31
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|roma}} → -1
  • {{#invoke:String|procura|O rato roeu a roupa do rei de Roma|Romeu}} → -1
Ver também
mw.ustring.find e {{str find}}

Função remove_first_word

{{#invoke:String|remove_first_word|1=texto}} ou {{#invoke:String|remove_first_word|texto}}

Remove a primeira palavra de texto. Por palavras entendem-se sequências de caracteres (strings) separadas por espaços.

  • {{#invoke:String|remove_first_word|Fôo bår bàz}} → bår bàz
  • {{#invoke:String|remove_first_word| Fôo bår bàz }} → bår bàz
  • {{#invoke:String|remove_first_word| a b }} → b
  • {{#invoke:String|remove_first_word|Fôo-bår}}
  • {{#invoke:String|remove_first_word|Fôo-bår bàz}} → bàz


Ver também

Esta documentação se encontra na subpágina Módulo:String/doc (editar | histórico)
Por favor inclua as categorias à subpágina /doc. Subpáginas deste módulo.

local str = {}
function str.len( frame )
	local new_args = str._getParameters( frame.args, {'s'} )
	local s = new_args['s'] or ''
	return mw.ustring.len( s )
end

--frame
function str.sub( frame )
	local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } )
	local s = new_args['s'] or ''
	local i = tonumber( new_args['i'] ) or 1
	local j = tonumber( new_args['j'] ) or -1
	local len = mw.ustring.len( s )
	if i < 0 then
		i = len + i + 1
	end
	if j < 0 then
		j = len + j + 1
	end
	if i > len or j > len or i < 1 or j < 1 then
		return str._error( 'Índice do subconjunto de strings fora do intervalo' )
	end
	if j < i then
		return str._error( 'Índices de subconjunto de strings fora de ordem' )
	end
	return mw.ustring.sub( s, i, j )
end

function str.sublength( frame )
	local i = tonumber( frame.args.i ) or 0
	local len = tonumber( frame.args.len )
	return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
end

--match
function str._match( s, pattern, start, match_index, plain_flag, nomatch )
	if s == '' then
		return str._error( 'A string de destino está vazia' )
	end
	if pattern == '' then
		return str._error( 'A string do padrão está vazia' )
	end
	start = tonumber(start) or 1
	if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
		return str._error( 'O início solicitado está fora do intervalo' )
	end
	if match_index == 0 then
		return str._error( 'O índice Match está fora do intervalo' )
	end
	if plain_flag then
		pattern = str._escapePattern( pattern )
	end
	local result
	if match_index == 1 then
		result = mw.ustring.match( s, pattern, start )
	else
		if start > 1 then
			s = mw.ustring.sub( s, start )
		end
		local iterator = mw.ustring.gmatch(s, pattern)
		if match_index > 0 then
			for w in iterator do
				match_index = match_index - 1
				if match_index == 0 then
					result = w
					break
				end
			end
		else
			local result_table = {}
			local count = 1
			for w in iterator do
				result_table[count] = w
				count = count + 1
			end

			result = result_table[ count + match_index ]
		end
	end
	if result == nil then
		if nomatch == nil then
			return str._error( 'Correspondência não encontrada' )
		else
			return nomatch
		end
	else
		return result
	end
end

--match
function str.match( frame )
	local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} )
	local s = new_args['s'] or ''
	local start = tonumber( new_args['start'] ) or 1
	local plain_flag = str._getBoolean( new_args['plain'] or false )
	local pattern = new_args['pattern'] or ''
	local match_index = math.floor( tonumber(new_args['match']) or 1 )
	local nomatch = new_args['nomatch']

	return str._match( s, pattern, start, match_index, plain_flag, nomatch )
end

--pos
function str.pos( frame )
	local new_args = str._getParameters( frame.args, {'target', 'pos'} )
	local target_str = new_args['target'] or ''
	local pos = tonumber( new_args['pos'] ) or 0

	if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
		return str._error( 'String index out of range' )
	end

	return mw.ustring.sub( target_str, pos, pos )
end

--str_find
function str.str_find( frame )
	local new_args = str._getParameters( frame.args, {'source', 'target'} )
	local source_str = new_args['source'] or ''
	local target_str = new_args['target'] or ''

	if target_str == '' then
		return 1
	end

	local start = mw.ustring.find( source_str, target_str, 1, true )
	if start == nil then
		start = -1
	end

	return start
end

--find
function str.find( frame )
	local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } )
	local source_str = new_args['source'] or ''
	local pattern = new_args['target'] or ''
	local start_pos = tonumber(new_args['start']) or 1
	local plain = new_args['plain'] or true

	if source_str == '' or pattern == '' then
		return 0
	end

	plain = str._getBoolean( plain )

	local start = mw.ustring.find( source_str, pattern, start_pos, plain )
	if start == nil then
		start = 0
	end

	return start
end

--replace
function str.replace( frame )
	local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } )
	local source_str = new_args['source'] or ''
	local pattern = new_args['pattern'] or ''
	local replace = new_args['replace'] or ''
	local count = tonumber( new_args['count'] )
	local plain = new_args['plain'] or true

	if source_str == '' or pattern == '' then
		return source_str
	end
	plain = str._getBoolean( plain )

	if plain then
		pattern = str._escapePattern( pattern )
		replace = mw.ustring.gsub( replace, "%%", "%%%%" ) --Only need to escape replacement sequences.
	end

	local result

	if count ~= nil then
		result = mw.ustring.gsub( source_str, pattern, replace, count )
	else
		result = mw.ustring.gsub( source_str, pattern, replace )
	end

	return result
end

--simple function to pipe string.rep to templates.
function str.rep( frame )
	local repetitions = tonumber( frame.args[2] )
	if not repetitions then
		return str._error( 'function rep expects a number as second parameter, received "' .. ( frame.args[2] or '' ) .. '"' )
	end
	return string.rep( frame.args[1] or '', repetitions )
end

--escapePattern
function str.escapePattern( frame )
	local pattern_str = frame.args[1]
	if not pattern_str then
		return str._error( 'Nenhuma sequência de padrão especificada' )
	end
	local result = str._escapePattern( pattern_str )
	return result
end

--função length

	function str.length(frame)
		local mystring = frame.args[1]
		return mw.ustring.len(mystring)
	end

--função substring
	function str.substring(frame)
		local mystring = frame.args[1]
		local i = tonumber(frame.args[2]) or 1
		local j = tonumber(frame.args[3]) or -1
		return mw.ustring.sub(mystring, i, j)
	end

--função charAt
	function str.charAt(frame)
		local mystring = frame.args[1] or ''
		local i = tonumber(frame.args[2]) or 0
		local stringlength = mw.ustring.len(mystring)
		if math.abs(i) > stringlength then
			return frame:expandTemplate{ title = 'erro', args = {
				'O índice fornecido está fora do escopo.'} }
		end
		if i == 0 then
			return "NULL"
		else
			return mw.ustring.sub(mystring, i, i)
		end
	end

--função repete
	function str.repete(frame)
		local mystring = frame.args[1]
		local n = tonumber(frame.args[2])
		if (n == nil) or (n < 1) then
			return frame:expandTemplate{ title = 'erro', args = {
				'O segundo parâmetro fornecido não é um inteiro positivo.'} }
		else
			return mw.ustring.rep(mystring, n)
		end
	end

--função procura
	function str.procura(frame)
		local mystring = frame.args[1]
		local substring = frame.args[2]
		local i = tonumber(frame.args[3]) or 1
		local result = mw.ustring.find(mystring, substring, i, true)
		if result == nil then
			return -1
		else
			return result
		end
	end

--função remove_first_word
	function str.remove_first_word(frame)
		local mystring = mw.text.trim(frame.args[1])
		if mw.ustring.find(mystring," ", 1, true) == nil then
			return ""
		else
			return mw.ustring.sub(mystring, tonumber(mw.ustring.find(mystring," ", 1, true)+1), -1)
		end
	end

--função remove_last_word
function str.remove_last_word(frame)
    local mystring = mw.text.trim(frame.args[1])
    if mw.ustring.find(mystring," ", 1, true) == nil then
        return ""
    else
        return mw.ustring.sub(mystring, 1, tonumber(mw.ustring.find(mystring," ", 1, true)-1))
    end
end

--count
function str.count(frame)
	local args = str._getParameters(frame.args, {'source', 'pattern', 'plain'})
	local source = args.source or ''
	local pattern = args.pattern or ''
	local plain = str._getBoolean(args.plain or true)
	if plain then
		pattern = str._escapePattern(pattern)
	end
	local _, count = mw.ustring.gsub(source, pattern, '')
	return count
end

--endswith
function str.endswith(frame)
	local args = str._getParameters(frame.args, {'source', 'pattern'})
	local source = args.source or ''
	local pattern = args.pattern or ''
	if pattern == '' then
		return "yes"
	end
	if mw.ustring.sub(source, -mw.ustring.len(pattern), -1) == pattern then
		return "yes"
	else
		return ""
	end
end

--join
function str.join(frame)
	local args = {}
	local sep
	for _, v in ipairs( frame.args ) do
		if sep then
			if v ~= '' then
				table.insert(args, v)
			end
		else
			sep = v
		end
	end
	return table.concat( args, sep or '' )
end

--Função auxiliar que preenche a lista de argumentos, dado que o usuário pode precisar usar uma combinação de parâmetros nomeados e não nomeados.
function str._getParameters( frame_args, arg_list )
	local new_args = {}
	local index = 1
	local value

	for _, arg in ipairs( arg_list ) do
		value = frame_args[arg]
		if value == nil then
			value = frame_args[index]
			index = index + 1
		end
		new_args[arg] = value
	end

	return new_args
end

--Mensagens de erro
function str._error( error_str )
	local frame = mw.getCurrentFrame()
	local error_category = frame.args.error_category or 'Erros relatados por módulo String'
	local ignore_errors = frame.args.ignore_errors or false
	local no_category = frame.args.no_category or false

	if str._getBoolean(ignore_errors) then
		return ''
	end

	local error_str = '<strong class="error">Erro: ' .. error_str .. '</strong>'
	if error_category ~= '' and not str._getBoolean( no_category ) then
		error_str = '[[Category:' .. error_category .. ']]' .. error_str
	end

	return error_str
end

--Função auxiliar para interpretar strings booleanas
function str._getBoolean( boolean_str )
	local boolean_value

	if type( boolean_str ) == 'string' then
		boolean_str = boolean_str:lower()
		if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'
				or boolean_str == '' then
			boolean_value = false
		else
			boolean_value = true
		end
	elseif type( boolean_str ) == 'boolean' then
		boolean_value = boolean_str
	else
		error( 'Nenhum valor booleano encontrado' )
	end
	return boolean_value
end

--Função auxiliar que escapa de todos os caracteres padrão para que sejam tratados como texto simples.
function str._escapePattern( pattern_str )
	return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" )
end

return str